From 91199ccb91a986d246ebef8e0d41278eefe417a8 Mon Sep 17 00:00:00 2001 From: Andrei Rebegea Date: Fri, 30 Mar 2018 16:30:10 +0300 Subject: [PATCH 1/9] REPO-3304: fix correct ignore path for helm --- .gitignore | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index d452a28934..4d1b992f33 100644 --- a/.gitignore +++ b/.gitignore @@ -30,5 +30,5 @@ hs_err_pid* # Alfresco alf_data/ -helm/alfresco-content-services/charts/* -helm/alfresco-content-services/requirements.lock \ No newline at end of file +helm/alfresco-content-services-community/charts/* +helm/alfresco-content-services-community/requirements.lock \ No newline at end of file From b877f52e6d385d270c1148982eb67433d81e17ad Mon Sep 17 00:00:00 2001 From: Alexandru-Eusebiu Epure Date: Mon, 2 Apr 2018 14:17:02 +0300 Subject: [PATCH 2/9] Merge feature/REPO-3378_simplify_project into master (#32) * REPO-3378: Integrate zip module into full-distribution module Rena,e full-distribution module to distribution. Remove zip module Remove zip module from the superPom --- distribution/pom.xml | 100 +++++++++-- .../src/assembly}/distribution.xml | 37 ++++- .../src/assembly/full-distribution.xml | 56 ------- .../src/main/resources/bin/apply_amps.bat | 0 .../src/main/resources/bin/apply_amps.sh | 0 .../src/main/resources/bin/clean_tomcat.bat | 0 .../src/main/resources/bin/clean_tomcat.sh | 0 .../licenses/3rd-party/Apache 2.0.txt | 0 .../licenses/3rd-party/Apache-like-JDOM.txt | 0 .../licenses/3rd-party/Apache-like-XPP.txt | 0 .../3rd-party/ApachePortableRuntime.txt | 0 .../BEA-JSR181-WebServicesMetadata.txt | 0 .../licenses/3rd-party/BSDlike-ASM.txt | 0 .../licenses/3rd-party/BSDlike-AntLR.txt | 0 .../licenses/3rd-party/BSDlike-Dojo.txt | 0 .../licenses/3rd-party/BSDlike-FreeMarker.txt | 0 .../licenses/3rd-party/BSDlike-FreeType.txt | 0 .../licenses/3rd-party/BSDlike-GIFLIB.txt | 0 .../licenses/3rd-party/BSDlike-Hamcrest.txt | 0 .../licenses/3rd-party/BSDlike-JGraph.txt | 0 .../licenses/3rd-party/BSDlike-Jaxen.txt | 0 .../licenses/3rd-party/BSDlike-JiBX.txt | 0 .../licenses/3rd-party/BSDlike-PostgreSQL.txt | 0 .../licenses/3rd-party/BSDlike-XMP.txt | 0 .../licenses/3rd-party/BSDlike-XStream.txt | 0 .../licenses/3rd-party/BSDlike-YUI.txt | 0 .../3rd-party/BSDlike-bubblinglibrary.txt | 0 .../licenses/3rd-party/BSDlike-dom4j.txt | 0 .../licenses/3rd-party/BSDlike-libjpeg.txt | 0 .../licenses/3rd-party/BSDlike-libpng.txt | 0 .../licenses/3rd-party/BSDlike-libtiff.txt | 0 .../licenses/3rd-party/BSDlike-staxutils.txt | 0 .../3rd-party/BSDlike-urlrewritefilter.txt | 0 .../3rd-party/BSDlike-yuicompressor.txt | 0 .../3rd-party/CC-BY-2.5-LightboxJS.txt | 0 .../3rd-party/CC-BY-3.0-jsTextReader.txt | 0 .../resources/licenses/3rd-party/CDDL-1.0.txt | 0 .../resources/licenses/3rd-party/CDDL-1.1.txt | 0 .../resources/licenses/3rd-party/CPL 1.0.txt | 0 .../3rd-party/Eclipse Public License.txt | 0 .../licenses/3rd-party/ICU License.txt | 0 .../3rd-party/ImageMagick-license.txt | 2 +- .../resources/licenses/3rd-party/JSON.txt | 0 .../resources/licenses/3rd-party/LGPL 2.1.txt | 0 .../resources/licenses/3rd-party/LGPL 3.txt | 0 .../resources/licenses/3rd-party/LGPL-2.0.txt | 0 .../licenses/3rd-party/MIT-CodeMirror.txt | 0 .../licenses/3rd-party/MIT-DateFormatJS.txt | 0 .../licenses/3rd-party/MIT-EnumJS.txt | 0 .../licenses/3rd-party/MIT-FullCalendar.txt | 0 .../licenses/3rd-party/MIT-extMouseWheel.txt | 0 .../licenses/3rd-party/MIT-jquery.txt | 0 .../licenses/3rd-party/MIT-jqueryui.txt | 0 .../licenses/3rd-party/MIT-jutf7.txt | 0 .../licenses/3rd-party/MIT-slf4j.txt | 0 .../resources/licenses/3rd-party/MPL-1.1.txt | 0 .../resources/licenses/3rd-party/MPL-2.0.txt | 0 .../3rd-party/OracleBinaryCode-Java.txt | 0 .../licenses/3rd-party/Sun Public License.txt | 0 .../Sun-JSR250-CommonsAnnotations.txt | 0 .../3rd-party/Sun-JSR907-TransactionAPI.txt | 0 .../3rd-party/Unidata Free Software.txt | 0 .../3rd-party/bouncycastle-license.txt | 0 .../resources/licenses/3rd-party/gpl-2.0.txt | 0 .../licenses/3rd-party/libreoffice.txt | 0 .../resources/licenses/3rd-party/openssl.txt | 0 .../resources/licenses/3rd-party/pdfium.txt | 0 .../resources/licenses/3rd-party/tomcat.txt | 0 .../licenses/3rd-party/xpdf-japanese.txt | 0 .../resources/licenses/3rd-party/zlib.txt | 0 .../src/main/resources/licenses/license.txt | 0 .../src/main/resources/licenses/notice.txt | 0 .../conf/Catalina/localhost/alfresco.xml | 0 pom.xml | 1 - zip/pom.xml | 155 ------------------ zip/src/main/resources/README.txt | 6 - 76 files changed, 118 insertions(+), 239 deletions(-) rename {zip/src/assemblies => distribution/src/assembly}/distribution.xml (73%) delete mode 100644 distribution/src/assembly/full-distribution.xml rename {zip => distribution}/src/main/resources/bin/apply_amps.bat (100%) rename {zip => distribution}/src/main/resources/bin/apply_amps.sh (100%) mode change 100755 => 100644 rename {zip => distribution}/src/main/resources/bin/clean_tomcat.bat (100%) rename {zip => distribution}/src/main/resources/bin/clean_tomcat.sh (100%) mode change 100755 => 100644 rename {zip => distribution}/src/main/resources/licenses/3rd-party/Apache 2.0.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/Apache-like-JDOM.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/Apache-like-XPP.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/ApachePortableRuntime.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BEA-JSR181-WebServicesMetadata.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-ASM.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-AntLR.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-Dojo.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-FreeMarker.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-FreeType.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-GIFLIB.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-Hamcrest.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-JGraph.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-Jaxen.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-JiBX.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-PostgreSQL.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-XMP.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-XStream.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-YUI.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-bubblinglibrary.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-dom4j.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-libjpeg.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-libpng.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-libtiff.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-staxutils.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-urlrewritefilter.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/BSDlike-yuicompressor.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/CC-BY-2.5-LightboxJS.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/CC-BY-3.0-jsTextReader.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/CDDL-1.0.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/CDDL-1.1.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/CPL 1.0.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/Eclipse Public License.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/ICU License.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/ImageMagick-license.txt (99%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/JSON.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/LGPL 2.1.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/LGPL 3.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/LGPL-2.0.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/MIT-CodeMirror.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/MIT-DateFormatJS.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/MIT-EnumJS.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/MIT-FullCalendar.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/MIT-extMouseWheel.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/MIT-jquery.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/MIT-jqueryui.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/MIT-jutf7.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/MIT-slf4j.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/MPL-1.1.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/MPL-2.0.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/OracleBinaryCode-Java.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/Sun Public License.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/Sun-JSR250-CommonsAnnotations.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/Sun-JSR907-TransactionAPI.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/Unidata Free Software.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/bouncycastle-license.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/gpl-2.0.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/libreoffice.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/openssl.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/pdfium.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/tomcat.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/xpdf-japanese.txt (100%) rename {zip => distribution}/src/main/resources/licenses/3rd-party/zlib.txt (100%) rename {zip => distribution}/src/main/resources/licenses/license.txt (100%) rename {zip => distribution}/src/main/resources/licenses/notice.txt (100%) rename {zip => distribution}/src/main/resources/web-server/conf/Catalina/localhost/alfresco.xml (100%) delete mode 100644 zip/pom.xml delete mode 100644 zip/src/main/resources/README.txt diff --git a/distribution/pom.xml b/distribution/pom.xml index d043fdf570..8f7efb558e 100644 --- a/distribution/pom.xml +++ b/distribution/pom.xml @@ -1,7 +1,7 @@ 4.0.0 - alfresco-content-services-community-full-distribution - Alfresco Content Services Community Full Distribution zip + alfresco-content-services-community-distribution + Alfresco Content Services Community Distribution zip jar @@ -12,18 +12,50 @@ + org.alfresco - alfresco-content-services-community-distribution + content-services-community ${project.version} - zip - - - * - * - - + war + + org.alfresco + alfresco-repository + + + org.alfresco + alfresco-data-model + + + org.alfresco + alfresco-server-root + war + + + org.alfresco + alfresco-mmt + + + + org.postgresql + postgresql + ${dependency.postgresql.version} + + + + org.alfresco + alfresco-pdf-renderer + linux + tgz + + + org.alfresco + alfresco-pdf-renderer + win64 + tgz + + org.alfresco alfresco-solr4-distribution @@ -35,6 +67,7 @@ + org.alfresco alfresco-content-services-share-distribution @@ -49,7 +82,7 @@ - ${project.artifactId}-${installer.version.name} + ${project.artifactId}-${project.version} src/main/resources @@ -68,11 +101,13 @@ + org.alfresco - alfresco-content-services-community-distribution - zip + alfresco-repository + alfresco/keystore/** + org.alfresco alfresco-solr4-distribution @@ -87,6 +122,43 @@ + + extract-jlan-dll + generate-resources + + unpack + + + + + org.alfresco + alfresco-jlan-embed + windll + *.dll + + + + + + + + copy-resources + generate-resources + + copy + + + + + org.alfresco + alfresco-server-root + war + ${project.build.outputDirectory}/web-server/webapps + ROOT.war + + + + @@ -102,7 +174,7 @@ false - src/assembly/full-distribution.xml + src/assembly/distribution.xml diff --git a/zip/src/assemblies/distribution.xml b/distribution/src/assembly/distribution.xml similarity index 73% rename from zip/src/assemblies/distribution.xml rename to distribution/src/assembly/distribution.xml index 7c12fe2936..e7958fc8e1 100644 --- a/zip/src/assemblies/distribution.xml +++ b/distribution/src/assembly/distribution.xml @@ -1,6 +1,8 @@ - warinstallation + xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd"> + distribution + + zip @@ -29,14 +31,37 @@ *.dll - + + - src/assembly - web-server/endorsed + ${project.build.directory}/dependency/solr4 + solr4 - * + solr4.war + + ${project.build.directory}/dependency/solr4 + web-server/webapps + + solr4.war + + + + + + ${project.build.directory}/dependency/alfresco-content-services-share-distribution-${alfresco.share.version} + + + web-server/** + modules/** + amps/** + + + + ${project.build.directory}/dependency/alfresco-content-services-share-distribution-${alfresco.share.version}/web-extension-samples + web-server/shared/classes/alfresco/web-extension + diff --git a/distribution/src/assembly/full-distribution.xml b/distribution/src/assembly/full-distribution.xml deleted file mode 100644 index 3aeb874f79..0000000000 --- a/distribution/src/assembly/full-distribution.xml +++ /dev/null @@ -1,56 +0,0 @@ - - distribution - - false - - - zip - - - - - - target/classes - - - - - - ${project.build.directory}/dependency/alfresco-content-services-community-distribution-${project.version} - - - - - - ${project.build.directory}/dependency/solr4 - solr4 - - solr4.war - - - - ${project.build.directory}/dependency/solr4 - web-server/webapps - - solr4.war - - - - - - ${project.build.directory}/dependency/alfresco-content-services-share-distribution-${alfresco.share.version} - - - web-server/** - modules/** - amps/** - - - - ${project.build.directory}/dependency/alfresco-content-services-share-distribution-${alfresco.share.version}/web-extension-samples - web-server/shared/classes/alfresco/web-extension - - - - diff --git a/zip/src/main/resources/bin/apply_amps.bat b/distribution/src/main/resources/bin/apply_amps.bat similarity index 100% rename from zip/src/main/resources/bin/apply_amps.bat rename to distribution/src/main/resources/bin/apply_amps.bat diff --git a/zip/src/main/resources/bin/apply_amps.sh b/distribution/src/main/resources/bin/apply_amps.sh old mode 100755 new mode 100644 similarity index 100% rename from zip/src/main/resources/bin/apply_amps.sh rename to distribution/src/main/resources/bin/apply_amps.sh diff --git a/zip/src/main/resources/bin/clean_tomcat.bat b/distribution/src/main/resources/bin/clean_tomcat.bat similarity index 100% rename from zip/src/main/resources/bin/clean_tomcat.bat rename to distribution/src/main/resources/bin/clean_tomcat.bat diff --git a/zip/src/main/resources/bin/clean_tomcat.sh b/distribution/src/main/resources/bin/clean_tomcat.sh old mode 100755 new mode 100644 similarity index 100% rename from zip/src/main/resources/bin/clean_tomcat.sh rename to distribution/src/main/resources/bin/clean_tomcat.sh diff --git a/zip/src/main/resources/licenses/3rd-party/Apache 2.0.txt b/distribution/src/main/resources/licenses/3rd-party/Apache 2.0.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/Apache 2.0.txt rename to distribution/src/main/resources/licenses/3rd-party/Apache 2.0.txt diff --git a/zip/src/main/resources/licenses/3rd-party/Apache-like-JDOM.txt b/distribution/src/main/resources/licenses/3rd-party/Apache-like-JDOM.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/Apache-like-JDOM.txt rename to distribution/src/main/resources/licenses/3rd-party/Apache-like-JDOM.txt diff --git a/zip/src/main/resources/licenses/3rd-party/Apache-like-XPP.txt b/distribution/src/main/resources/licenses/3rd-party/Apache-like-XPP.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/Apache-like-XPP.txt rename to distribution/src/main/resources/licenses/3rd-party/Apache-like-XPP.txt diff --git a/zip/src/main/resources/licenses/3rd-party/ApachePortableRuntime.txt b/distribution/src/main/resources/licenses/3rd-party/ApachePortableRuntime.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/ApachePortableRuntime.txt rename to distribution/src/main/resources/licenses/3rd-party/ApachePortableRuntime.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BEA-JSR181-WebServicesMetadata.txt b/distribution/src/main/resources/licenses/3rd-party/BEA-JSR181-WebServicesMetadata.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BEA-JSR181-WebServicesMetadata.txt rename to distribution/src/main/resources/licenses/3rd-party/BEA-JSR181-WebServicesMetadata.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-ASM.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-ASM.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-ASM.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-ASM.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-AntLR.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-AntLR.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-AntLR.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-AntLR.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-Dojo.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-Dojo.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-Dojo.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-Dojo.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-FreeMarker.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-FreeMarker.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-FreeMarker.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-FreeMarker.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-FreeType.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-FreeType.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-FreeType.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-FreeType.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-GIFLIB.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-GIFLIB.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-GIFLIB.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-GIFLIB.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-Hamcrest.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-Hamcrest.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-Hamcrest.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-Hamcrest.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-JGraph.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-JGraph.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-JGraph.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-JGraph.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-Jaxen.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-Jaxen.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-Jaxen.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-Jaxen.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-JiBX.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-JiBX.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-JiBX.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-JiBX.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-PostgreSQL.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-PostgreSQL.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-PostgreSQL.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-PostgreSQL.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-XMP.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-XMP.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-XMP.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-XMP.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-XStream.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-XStream.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-XStream.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-XStream.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-YUI.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-YUI.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-YUI.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-YUI.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-bubblinglibrary.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-bubblinglibrary.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-bubblinglibrary.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-bubblinglibrary.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-dom4j.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-dom4j.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-dom4j.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-dom4j.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-libjpeg.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-libjpeg.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-libjpeg.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-libjpeg.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-libpng.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-libpng.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-libpng.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-libpng.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-libtiff.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-libtiff.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-libtiff.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-libtiff.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-staxutils.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-staxutils.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-staxutils.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-staxutils.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-urlrewritefilter.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-urlrewritefilter.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-urlrewritefilter.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-urlrewritefilter.txt diff --git a/zip/src/main/resources/licenses/3rd-party/BSDlike-yuicompressor.txt b/distribution/src/main/resources/licenses/3rd-party/BSDlike-yuicompressor.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/BSDlike-yuicompressor.txt rename to distribution/src/main/resources/licenses/3rd-party/BSDlike-yuicompressor.txt diff --git a/zip/src/main/resources/licenses/3rd-party/CC-BY-2.5-LightboxJS.txt b/distribution/src/main/resources/licenses/3rd-party/CC-BY-2.5-LightboxJS.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/CC-BY-2.5-LightboxJS.txt rename to distribution/src/main/resources/licenses/3rd-party/CC-BY-2.5-LightboxJS.txt diff --git a/zip/src/main/resources/licenses/3rd-party/CC-BY-3.0-jsTextReader.txt b/distribution/src/main/resources/licenses/3rd-party/CC-BY-3.0-jsTextReader.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/CC-BY-3.0-jsTextReader.txt rename to distribution/src/main/resources/licenses/3rd-party/CC-BY-3.0-jsTextReader.txt diff --git a/zip/src/main/resources/licenses/3rd-party/CDDL-1.0.txt b/distribution/src/main/resources/licenses/3rd-party/CDDL-1.0.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/CDDL-1.0.txt rename to distribution/src/main/resources/licenses/3rd-party/CDDL-1.0.txt diff --git a/zip/src/main/resources/licenses/3rd-party/CDDL-1.1.txt b/distribution/src/main/resources/licenses/3rd-party/CDDL-1.1.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/CDDL-1.1.txt rename to distribution/src/main/resources/licenses/3rd-party/CDDL-1.1.txt diff --git a/zip/src/main/resources/licenses/3rd-party/CPL 1.0.txt b/distribution/src/main/resources/licenses/3rd-party/CPL 1.0.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/CPL 1.0.txt rename to distribution/src/main/resources/licenses/3rd-party/CPL 1.0.txt diff --git a/zip/src/main/resources/licenses/3rd-party/Eclipse Public License.txt b/distribution/src/main/resources/licenses/3rd-party/Eclipse Public License.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/Eclipse Public License.txt rename to distribution/src/main/resources/licenses/3rd-party/Eclipse Public License.txt diff --git a/zip/src/main/resources/licenses/3rd-party/ICU License.txt b/distribution/src/main/resources/licenses/3rd-party/ICU License.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/ICU License.txt rename to distribution/src/main/resources/licenses/3rd-party/ICU License.txt diff --git a/zip/src/main/resources/licenses/3rd-party/ImageMagick-license.txt b/distribution/src/main/resources/licenses/3rd-party/ImageMagick-license.txt similarity index 99% rename from zip/src/main/resources/licenses/3rd-party/ImageMagick-license.txt rename to distribution/src/main/resources/licenses/3rd-party/ImageMagick-license.txt index 1f4c6c89db..fac88bf9ef 100644 --- a/zip/src/main/resources/licenses/3rd-party/ImageMagick-license.txt +++ b/distribution/src/main/resources/licenses/3rd-party/ImageMagick-license.txt @@ -107,4 +107,4 @@ To apply the ImageMagick License to your work, attach the following boilerplate 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. + under the License. \ No newline at end of file diff --git a/zip/src/main/resources/licenses/3rd-party/JSON.txt b/distribution/src/main/resources/licenses/3rd-party/JSON.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/JSON.txt rename to distribution/src/main/resources/licenses/3rd-party/JSON.txt diff --git a/zip/src/main/resources/licenses/3rd-party/LGPL 2.1.txt b/distribution/src/main/resources/licenses/3rd-party/LGPL 2.1.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/LGPL 2.1.txt rename to distribution/src/main/resources/licenses/3rd-party/LGPL 2.1.txt diff --git a/zip/src/main/resources/licenses/3rd-party/LGPL 3.txt b/distribution/src/main/resources/licenses/3rd-party/LGPL 3.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/LGPL 3.txt rename to distribution/src/main/resources/licenses/3rd-party/LGPL 3.txt diff --git a/zip/src/main/resources/licenses/3rd-party/LGPL-2.0.txt b/distribution/src/main/resources/licenses/3rd-party/LGPL-2.0.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/LGPL-2.0.txt rename to distribution/src/main/resources/licenses/3rd-party/LGPL-2.0.txt diff --git a/zip/src/main/resources/licenses/3rd-party/MIT-CodeMirror.txt b/distribution/src/main/resources/licenses/3rd-party/MIT-CodeMirror.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/MIT-CodeMirror.txt rename to distribution/src/main/resources/licenses/3rd-party/MIT-CodeMirror.txt diff --git a/zip/src/main/resources/licenses/3rd-party/MIT-DateFormatJS.txt b/distribution/src/main/resources/licenses/3rd-party/MIT-DateFormatJS.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/MIT-DateFormatJS.txt rename to distribution/src/main/resources/licenses/3rd-party/MIT-DateFormatJS.txt diff --git a/zip/src/main/resources/licenses/3rd-party/MIT-EnumJS.txt b/distribution/src/main/resources/licenses/3rd-party/MIT-EnumJS.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/MIT-EnumJS.txt rename to distribution/src/main/resources/licenses/3rd-party/MIT-EnumJS.txt diff --git a/zip/src/main/resources/licenses/3rd-party/MIT-FullCalendar.txt b/distribution/src/main/resources/licenses/3rd-party/MIT-FullCalendar.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/MIT-FullCalendar.txt rename to distribution/src/main/resources/licenses/3rd-party/MIT-FullCalendar.txt diff --git a/zip/src/main/resources/licenses/3rd-party/MIT-extMouseWheel.txt b/distribution/src/main/resources/licenses/3rd-party/MIT-extMouseWheel.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/MIT-extMouseWheel.txt rename to distribution/src/main/resources/licenses/3rd-party/MIT-extMouseWheel.txt diff --git a/zip/src/main/resources/licenses/3rd-party/MIT-jquery.txt b/distribution/src/main/resources/licenses/3rd-party/MIT-jquery.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/MIT-jquery.txt rename to distribution/src/main/resources/licenses/3rd-party/MIT-jquery.txt diff --git a/zip/src/main/resources/licenses/3rd-party/MIT-jqueryui.txt b/distribution/src/main/resources/licenses/3rd-party/MIT-jqueryui.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/MIT-jqueryui.txt rename to distribution/src/main/resources/licenses/3rd-party/MIT-jqueryui.txt diff --git a/zip/src/main/resources/licenses/3rd-party/MIT-jutf7.txt b/distribution/src/main/resources/licenses/3rd-party/MIT-jutf7.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/MIT-jutf7.txt rename to distribution/src/main/resources/licenses/3rd-party/MIT-jutf7.txt diff --git a/zip/src/main/resources/licenses/3rd-party/MIT-slf4j.txt b/distribution/src/main/resources/licenses/3rd-party/MIT-slf4j.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/MIT-slf4j.txt rename to distribution/src/main/resources/licenses/3rd-party/MIT-slf4j.txt diff --git a/zip/src/main/resources/licenses/3rd-party/MPL-1.1.txt b/distribution/src/main/resources/licenses/3rd-party/MPL-1.1.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/MPL-1.1.txt rename to distribution/src/main/resources/licenses/3rd-party/MPL-1.1.txt diff --git a/zip/src/main/resources/licenses/3rd-party/MPL-2.0.txt b/distribution/src/main/resources/licenses/3rd-party/MPL-2.0.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/MPL-2.0.txt rename to distribution/src/main/resources/licenses/3rd-party/MPL-2.0.txt diff --git a/zip/src/main/resources/licenses/3rd-party/OracleBinaryCode-Java.txt b/distribution/src/main/resources/licenses/3rd-party/OracleBinaryCode-Java.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/OracleBinaryCode-Java.txt rename to distribution/src/main/resources/licenses/3rd-party/OracleBinaryCode-Java.txt diff --git a/zip/src/main/resources/licenses/3rd-party/Sun Public License.txt b/distribution/src/main/resources/licenses/3rd-party/Sun Public License.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/Sun Public License.txt rename to distribution/src/main/resources/licenses/3rd-party/Sun Public License.txt diff --git a/zip/src/main/resources/licenses/3rd-party/Sun-JSR250-CommonsAnnotations.txt b/distribution/src/main/resources/licenses/3rd-party/Sun-JSR250-CommonsAnnotations.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/Sun-JSR250-CommonsAnnotations.txt rename to distribution/src/main/resources/licenses/3rd-party/Sun-JSR250-CommonsAnnotations.txt diff --git a/zip/src/main/resources/licenses/3rd-party/Sun-JSR907-TransactionAPI.txt b/distribution/src/main/resources/licenses/3rd-party/Sun-JSR907-TransactionAPI.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/Sun-JSR907-TransactionAPI.txt rename to distribution/src/main/resources/licenses/3rd-party/Sun-JSR907-TransactionAPI.txt diff --git a/zip/src/main/resources/licenses/3rd-party/Unidata Free Software.txt b/distribution/src/main/resources/licenses/3rd-party/Unidata Free Software.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/Unidata Free Software.txt rename to distribution/src/main/resources/licenses/3rd-party/Unidata Free Software.txt diff --git a/zip/src/main/resources/licenses/3rd-party/bouncycastle-license.txt b/distribution/src/main/resources/licenses/3rd-party/bouncycastle-license.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/bouncycastle-license.txt rename to distribution/src/main/resources/licenses/3rd-party/bouncycastle-license.txt diff --git a/zip/src/main/resources/licenses/3rd-party/gpl-2.0.txt b/distribution/src/main/resources/licenses/3rd-party/gpl-2.0.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/gpl-2.0.txt rename to distribution/src/main/resources/licenses/3rd-party/gpl-2.0.txt diff --git a/zip/src/main/resources/licenses/3rd-party/libreoffice.txt b/distribution/src/main/resources/licenses/3rd-party/libreoffice.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/libreoffice.txt rename to distribution/src/main/resources/licenses/3rd-party/libreoffice.txt diff --git a/zip/src/main/resources/licenses/3rd-party/openssl.txt b/distribution/src/main/resources/licenses/3rd-party/openssl.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/openssl.txt rename to distribution/src/main/resources/licenses/3rd-party/openssl.txt diff --git a/zip/src/main/resources/licenses/3rd-party/pdfium.txt b/distribution/src/main/resources/licenses/3rd-party/pdfium.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/pdfium.txt rename to distribution/src/main/resources/licenses/3rd-party/pdfium.txt diff --git a/zip/src/main/resources/licenses/3rd-party/tomcat.txt b/distribution/src/main/resources/licenses/3rd-party/tomcat.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/tomcat.txt rename to distribution/src/main/resources/licenses/3rd-party/tomcat.txt diff --git a/zip/src/main/resources/licenses/3rd-party/xpdf-japanese.txt b/distribution/src/main/resources/licenses/3rd-party/xpdf-japanese.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/xpdf-japanese.txt rename to distribution/src/main/resources/licenses/3rd-party/xpdf-japanese.txt diff --git a/zip/src/main/resources/licenses/3rd-party/zlib.txt b/distribution/src/main/resources/licenses/3rd-party/zlib.txt similarity index 100% rename from zip/src/main/resources/licenses/3rd-party/zlib.txt rename to distribution/src/main/resources/licenses/3rd-party/zlib.txt diff --git a/zip/src/main/resources/licenses/license.txt b/distribution/src/main/resources/licenses/license.txt similarity index 100% rename from zip/src/main/resources/licenses/license.txt rename to distribution/src/main/resources/licenses/license.txt diff --git a/zip/src/main/resources/licenses/notice.txt b/distribution/src/main/resources/licenses/notice.txt similarity index 100% rename from zip/src/main/resources/licenses/notice.txt rename to distribution/src/main/resources/licenses/notice.txt diff --git a/zip/src/main/resources/web-server/conf/Catalina/localhost/alfresco.xml b/distribution/src/main/resources/web-server/conf/Catalina/localhost/alfresco.xml similarity index 100% rename from zip/src/main/resources/web-server/conf/Catalina/localhost/alfresco.xml rename to distribution/src/main/resources/web-server/conf/Catalina/localhost/alfresco.xml diff --git a/pom.xml b/pom.xml index a33e131653..a3c8d0b4c9 100644 --- a/pom.xml +++ b/pom.xml @@ -32,7 +32,6 @@ war - zip distribution public-javadoc docker-alfresco diff --git a/zip/pom.xml b/zip/pom.xml deleted file mode 100644 index 8e83577930..0000000000 --- a/zip/pom.xml +++ /dev/null @@ -1,155 +0,0 @@ - - 4.0.0 - alfresco-content-services-community-distribution - Alfresco Content Services Community zip (WAR Installation) - jar - - - org.alfresco - acs-community-packaging - 6.0.5-SNAPSHOT - ../pom.xml - - - - - - org.alfresco - content-services-community - ${project.version} - war - - - org.alfresco - alfresco-repository - - - org.alfresco - alfresco-data-model - - - org.alfresco - alfresco-server-root - war - - - org.alfresco - alfresco-mmt - - - - org.postgresql - postgresql - ${dependency.postgresql.version} - - - - org.alfresco - alfresco-pdf-renderer - linux - tgz - - - org.alfresco - alfresco-pdf-renderer - win64 - tgz - - - - - - ${project.artifactId}-${project.version} - - - - src/main/resources - true - - - - - maven-dependency-plugin - - - - extract-keystore - generate-resources - - unpack - - - - - org.alfresco - alfresco-repository - alfresco/keystore/** - - - - - - - - extract-jlan-dll - generate-resources - - unpack - - - - - org.alfresco - alfresco-jlan-embed - windll - *.dll - - - - - - - - copy-resources - generate-resources - - copy - - - - - org.alfresco - alfresco-server-root - war - ${project.build.outputDirectory}/web-server/webapps - ROOT.war - - - - - - - - - - maven-assembly-plugin - - - make-assembly - package - - single - - - - - false - - src/assemblies/distribution.xml - - - - - - - \ No newline at end of file diff --git a/zip/src/main/resources/README.txt b/zip/src/main/resources/README.txt deleted file mode 100644 index 5eb415d327..0000000000 --- a/zip/src/main/resources/README.txt +++ /dev/null @@ -1,6 +0,0 @@ -Alfresco Content Services Community ${project.version} -====================== - -For users of Alfresco Community Edition, more information on this release is available at https://community.alfresco.com/community/ecm. - - From 76d90bcadb1da1003aec8a2225077d72e5d86cbd Mon Sep 17 00:00:00 2001 From: Alexandru-Eusebiu Epure Date: Mon, 2 Apr 2018 16:04:44 +0300 Subject: [PATCH 3/9] REPO-3378: update Dockerfile ENV variables to point to the corect imagemagick,libreoffice and pdfium license url. --- docker-alfresco/Dockerfile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docker-alfresco/Dockerfile b/docker-alfresco/Dockerfile index 2afd563928..d66976aaeb 100644 --- a/docker-alfresco/Dockerfile +++ b/docker-alfresco/Dockerfile @@ -10,14 +10,14 @@ FROM quay.io/alfresco/alfresco-base-tomcat:8.5.28-java-8-oracle-centos-7-f7b1278 # LibreOffice is from The Document Foundation. See the license at https://www.libreoffice.org/download/license/ or in /libreoffice.txt ENV ALFRESCO_PDF_RENDERER_LIB_RPM_URL=https://nexus.alfresco.com/nexus/service/local/repositories/releases/content/org/alfresco/alfresco-pdf-renderer/1.1/alfresco-pdf-renderer-1.1-linux.tgz -ENV PDFIUM_LICENSE_FILE=https://github.com/Alfresco/acs-community-packaging/blob/master/zip/src/main/resources/licenses/3rd-party/pdfium.txt +ENV PDFIUM_LICENSE_FILE=https://github.com/Alfresco/acs-community-packaging/blob/master/distribution/src/main/resources/licenses/3rd-party/pdfium.txt ENV LIBREOFFICE_RPM_URL=https://nexus.alfresco.com/nexus/service/local/repositories/thirdparty/content/org/libreoffice/libreoffice-dist/5.4.6/libreoffice-dist-5.4.6-linux.gz -ENV LIBREOFFICE_LICENSE_FILE=https://github.com/Alfresco/acs-community-packaging/blob/master/zip/src/main/resources/licenses/3rd-party/libreoffice.txt +ENV LIBREOFFICE_LICENSE_FILE=https://github.com/Alfresco/acs-community-packaging/blob/master/distribution/src/main/resources/licenses/3rd-party/libreoffice.txt ENV IMAGEMAGICK_RPM_URL=https://nexus.alfresco.com/nexus/service/local/repositories/thirdparty/content/org/imagemagick/imagemagick-distribution/7.0.7-27/imagemagick-distribution-7.0.7-27-linux.rpm ENV IMAGEMAGICK_LIB_RPM_URL=https://nexus.alfresco.com/nexus/service/local/repositories/thirdparty/content/org/imagemagick/imagemagick-distribution/7.0.7-27/imagemagick-distribution-7.0.7-27-libs-linux.rpm -ENV IMAGEMAGICK_LICENSE_FILE=https://github.com/Alfresco/acs-community-packaging/blob/master/zip/src/main/resources/licenses/3rd-party/ImageMagick-license.txt +ENV IMAGEMAGICK_LICENSE_FILE=https://github.com/Alfresco/acs-community-packaging/blob/master/distribution/src/main/resources/licenses/3rd-party/ImageMagick-license.txt RUN yum install wget -y && \ \ From af691d2c917ed5e610d3a59010d44054346d118e Mon Sep 17 00:00:00 2001 From: Alexandru-Eusebiu Epure Date: Mon, 2 Apr 2018 17:37:30 +0300 Subject: [PATCH 4/9] REPO-3392: Remove jboss-web.xml and weblogic.xml --- war/src/main/webapp/WEB-INF/jboss-web.xml | 18 ------------------ war/src/main/webapp/WEB-INF/weblogic.xml | 8 -------- 2 files changed, 26 deletions(-) delete mode 100644 war/src/main/webapp/WEB-INF/jboss-web.xml delete mode 100644 war/src/main/webapp/WEB-INF/weblogic.xml diff --git a/war/src/main/webapp/WEB-INF/jboss-web.xml b/war/src/main/webapp/WEB-INF/jboss-web.xml deleted file mode 100644 index f0343eaed5..0000000000 --- a/war/src/main/webapp/WEB-INF/jboss-web.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - jdbc/dataSource - java:jboss/datasources/MySqlDS - - - jdbc/activitiIdGeneratorDataSource - java:jboss/datasources/MySqlDS - - diff --git a/war/src/main/webapp/WEB-INF/weblogic.xml b/war/src/main/webapp/WEB-INF/weblogic.xml deleted file mode 100644 index 2579eacdf8..0000000000 --- a/war/src/main/webapp/WEB-INF/weblogic.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - -true - - - \ No newline at end of file From 3ea5cb0e2d150ed3a0549b0838fee2f6adee981d Mon Sep 17 00:00:00 2001 From: CodrinChirica Date: Tue, 3 Apr 2018 10:34:50 +0300 Subject: [PATCH 5/9] Upgrade data-model to 8.3 and alfresco-repository to 6.40 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index a3c8d0b4c9..95649cd872 100644 --- a/pom.xml +++ b/pom.xml @@ -63,8 +63,8 @@ latest 7.1 - 8.2 - 6.38 + 8.3 + 6.40 6.25 1.0.7 From 19340a666dcd43be86bf0f942a23ea2a928e2a4a Mon Sep 17 00:00:00 2001 From: Andrei Rebegea Date: Tue, 3 Apr 2018 13:17:40 +0300 Subject: [PATCH 6/9] REPO-3304: add persisted volume clame to make the community chart independent --- .gitignore | 3 ++- .../templates/pvc-acs.yaml | 10 ++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 helm/alfresco-content-services-community/templates/pvc-acs.yaml diff --git a/.gitignore b/.gitignore index 4d1b992f33..5e7beabdd0 100644 --- a/.gitignore +++ b/.gitignore @@ -31,4 +31,5 @@ hs_err_pid* alf_data/ helm/alfresco-content-services-community/charts/* -helm/alfresco-content-services-community/requirements.lock \ No newline at end of file +helm/alfresco-content-services-community/requirements.lock +helm/alfresco-content-services-community*.tgz \ No newline at end of file diff --git a/helm/alfresco-content-services-community/templates/pvc-acs.yaml b/helm/alfresco-content-services-community/templates/pvc-acs.yaml new file mode 100644 index 0000000000..3812662175 --- /dev/null +++ b/helm/alfresco-content-services-community/templates/pvc-acs.yaml @@ -0,0 +1,10 @@ +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: alfresco-volume-claim +spec: + accessModes: + - ReadWriteOnce + resources: + requests: + storage: 5Gi \ No newline at end of file From adcf700d5c1d934b370e6203bf0cc4b601f5a071 Mon Sep 17 00:00:00 2001 From: CodrinChirica Date: Tue, 3 Apr 2018 13:47:06 +0300 Subject: [PATCH 7/9] Upgrade alfresco-remote-api to 6.26 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 95649cd872..226cd5936b 100644 --- a/pom.xml +++ b/pom.xml @@ -65,7 +65,7 @@ 7.1 8.3 6.40 - 6.25 + 6.26 1.0.7 6.0 From e3d7ff93a50c54a976653201c283733b32588e2a Mon Sep 17 00:00:00 2001 From: Alex Mukha Date: Tue, 3 Apr 2018 14:53:21 +0100 Subject: [PATCH 8/9] REPO-1294: EOL myfaces-api, myfaces-impl & jsp-api (#25) * REPO-1294: EOL myfaces-api, myfaces-impl & jsp-api - Remove JSF specific classes - Remove webclient config - Moved authentication filters to remote-api --- pom.xml | 10 - war/pom.xml | 6 - .../WebClientPortletAuthenticatorFactory.java | 113 - .../scripts/portlet/WebScriptRepoPortlet.java | 85 - .../scripts/servlet/AuthenticatorServlet.java | 88 - .../WebClientAuthenticatorFactory.java | 200 -- .../alfresco/web/action/ActionEvaluator.java | 63 - .../evaluator/AddTranslationEvaluator.java | 93 - .../action/evaluator/ApproveDocEvaluator.java | 59 - .../ApproveNonDraftDocEvaluator.java | 49 - .../action/evaluator/BaseActionEvaluator.java | 75 - .../evaluator/CancelCheckoutDocEvaluator.java | 50 - .../evaluator/CancelEditingDocEvaluator.java | 46 - .../evaluator/CancelWorkflowEvaluator.java | 84 - .../action/evaluator/CheckinDocEvaluator.java | 50 - .../evaluator/CheckoutDocEvaluator.java | 59 - .../evaluator/CreateForumMLNodeEvaluator.java | 55 - .../evaluator/CreateForumNodeEvaluator.java | 48 - .../action/evaluator/CutNodeEvaluator.java | 78 - .../action/evaluator/DeleteDocEvaluator.java | 84 - .../evaluator/DiscussNodeEvaluator.java | 72 - .../evaluator/DiscussionCopyEvaluator.java | 84 - .../evaluator/DiscussionCutEvaluator.java | 71 - .../evaluator/DoneEditingDocEvaluator.java | 46 - .../evaluator/EditDocCIFSEvaluator.java | 76 - .../evaluator/EditDocHttpEvaluator.java | 84 - .../evaluator/EditDocOfflineEvaluator.java | 34 - .../evaluator/EditDocOnlineCIFSEvaluator.java | 77 - .../evaluator/EditDocOnlineHttpEvaluator.java | 79 - .../EditDocOnlineWebDavEvaluator.java | 79 - .../evaluator/EditDocWebDavEvaluator.java | 75 - .../action/evaluator/EditPostEvaluator.java | 52 - .../evaluator/ForumsCheckinDocEvaluator.java | 79 - .../evaluator/GroupActionEvaluator.java | 67 - .../evaluator/MakeMultilingualEvaluator.java | 61 - .../MultilingualDetailsEvaluator.java | 46 - .../action/evaluator/NewEditionEvaluator.java | 50 - .../action/evaluator/RejectDocEvaluator.java | 47 - .../evaluator/RejectNonDraftDocEvaluator.java | 49 - .../evaluator/ShortcutNodeEvaluator.java | 52 - .../evaluator/StartWorkflowEvaluator.java | 70 - .../evaluator/TakeOwnershipDocEvaluator.java | 46 - .../action/evaluator/UnlockDocEvaluator.java | 60 - .../evaluator/UnlockedDocEvaluator.java | 46 - .../action/evaluator/UpdateDocEvaluator.java | 60 - .../evaluator/UploadNewVersionEvaluator.java | 47 - .../web/app/AlfrescoNavigationHandler.java | 1002 ------- .../org/alfresco/web/app/Application.java | 1258 --------- .../org/alfresco/web/app/ContextListener.java | 160 -- .../alfresco/web/app/DebugPhaseListener.java | 124 - .../web/app/ResourceBundleBootstrap.java | 50 - .../web/app/ResourceBundleWrapper.java | 327 --- .../web/app/context/IContextListener.java | 61 - .../web/app/context/UIContextService.java | 166 -- .../portlet/AlfrescoDefaultViewSelector.java | 68 - .../web/app/portlet/AlfrescoFacesPortlet.java | 748 ----- .../servlet/AbstractAuthenticationFilter.java | 182 -- .../web/app/servlet/AcceptLanguage.java | 138 - .../servlet/AdminAuthenticationFilter.java | 122 - .../servlet/AlfrescoX509ServletFilter.java | 81 - .../web/app/servlet/AuthenticationFilter.java | 129 - .../web/app/servlet/AuthenticationHelper.java | 777 ------ .../web/app/servlet/AuthenticationStatus.java | 34 - .../servlet/BaseDownloadContentServlet.java | 455 --- .../alfresco/web/app/servlet/BaseServlet.java | 507 ---- .../servlet/BaseTemplateContentServlet.java | 388 --- .../CmisSecurityContextCleanerFilter.java | 63 - .../web/app/servlet/CommandServlet.java | 273 -- .../app/servlet/DownloadContentServlet.java | 184 -- .../servlet/DownloadRawContentServlet.java | 213 -- .../app/servlet/ExternalAccessServlet.java | 360 --- .../alfresco/web/app/servlet/FacesHelper.java | 345 --- .../app/servlet/GlobalLocalizationFilter.java | 145 - .../servlet/GuestDownloadContentServlet.java | 155 -- .../servlet/GuestTemplateContentServlet.java | 196 -- .../HTTPRequestAuthenticationFilter.java | 295 -- .../servlet/KerberosAuthenticationFilter.java | 139 - .../web/app/servlet/ModeDetectionFilter.java | 79 - .../app/servlet/NTLMAuthenticationFilter.java | 136 - .../SecurityContextCleanupPhaseListener.java | 68 - .../app/servlet/TemplateContentServlet.java | 154 -- .../web/app/servlet/UploadContentServlet.java | 284 -- .../web/app/servlet/UploadFileServlet.java | 286 -- .../WebScriptSSOAuthenticationFilter.java | 132 - .../WebscriptCookieAuthenticationFilter.java | 104 - .../WorkflowDefinitionImageServlet.java | 80 - .../web/app/servlet/ajax/AjaxCommand.java | 62 - .../web/app/servlet/ajax/AjaxServlet.java | 222 -- .../web/app/servlet/ajax/BaseAjaxCommand.java | 44 - .../web/app/servlet/ajax/GetCommand.java | 94 - .../web/app/servlet/ajax/InvokeCommand.java | 243 -- .../command/ApproveWorkflowCommand.java | 70 - .../command/BaseNodeCommandProcessor.java | 72 - .../servlet/command/BaseUIActionCommand.java | 40 - .../web/app/servlet/command/Command.java | 53 - .../app/servlet/command/CommandFactory.java | 106 - .../app/servlet/command/CommandProcessor.java | 88 - .../command/EditContentPropertiesCommand.java | 97 - .../app/servlet/command/EditSpaceCommand.java | 97 - .../app/servlet/command/EndTaskCommand.java | 69 - .../servlet/command/ExecuteScriptCommand.java | 106 - .../servlet/command/ExtCommandProcessor.java | 60 - .../command/ManageTaskDialogCommand.java | 100 - .../command/RejectWorkflowCommand.java | 70 - .../command/ScriptCommandProcessor.java | 168 -- .../servlet/command/TaskCommandProcessor.java | 109 - .../command/UIActionCommandProcessor.java | 137 - .../command/UserProfileDialogCommand.java | 96 - .../command/WorkflowCommandProcessor.java | 84 - .../java/org/alfresco/web/bean/AboutBean.java | 113 - .../alfresco/web/bean/BaseDetailsBean.java | 753 ----- .../org/alfresco/web/bean/BrowseBean.java | 2450 ----------------- .../web/bean/CategoriesProperties.java | 169 -- .../web/bean/CategoryBrowserBean.java | 84 - .../java/org/alfresco/web/bean/ErrorBean.java | 113 - .../org/alfresco/web/bean/FileUploadBean.java | 101 - .../web/bean/LinkPropertiesDialog.java | 254 -- .../java/org/alfresco/web/bean/LoginBean.java | 559 ---- .../alfresco/web/bean/LoginOutcomeBean.java | 68 - .../web/bean/MultiValueEditorBean.java | 51 - .../org/alfresco/web/bean/NavigationBean.java | 1255 --------- .../alfresco/web/bean/NodeEventListener.java | 46 - .../org/alfresco/web/bean/SidebarBean.java | 197 -- .../web/bean/SpaceLinkDetailsDialog.java | 198 -- .../web/bean/TemplateMailHelperBean.java | 317 --- .../web/bean/TemplateSupportBean.java | 297 -- .../web/bean/actions/BaseActionWizard.java | 1156 -------- .../alfresco/web/bean/actions/IHandler.java | 102 - .../web/bean/actions/RunActionWizard.java | 205 -- .../actions/handlers/AddFeaturesHandler.java | 91 - .../actions/handlers/BaseActionHandler.java | 67 - .../bean/actions/handlers/CheckInHandler.java | 107 - .../actions/handlers/CheckOutHandler.java | 98 - .../bean/actions/handlers/CopyHandler.java | 89 - .../bean/actions/handlers/ImportHandler.java | 85 - .../actions/handlers/LinkCategoryHandler.java | 87 - .../bean/actions/handlers/MailHandler.java | 186 -- .../bean/actions/handlers/MoveHandler.java | 87 - .../handlers/RemoveFeaturesHandler.java | 92 - .../bean/actions/handlers/ScriptHandler.java | 83 - .../handlers/SimpleWorkflowHandler.java | 208 -- .../handlers/SpecialiseTypeHandler.java | 90 - .../actions/handlers/TransformHandler.java | 112 - .../handlers/TransformImageHandler.java | 122 - .../web/bean/admin/AdminConsoleDialog.java | 50 - .../web/bean/admin/AdminNodeBrowseBean.java | 1063 ------- .../bean/admin/ConfigAdminConsoleBean.java | 186 -- .../alfresco/web/bean/admin/ExportDialog.java | 324 --- .../alfresco/web/bean/admin/ImportDialog.java | 515 ---- .../web/bean/admin/ShowSystemInfoDialog.java | 86 - .../bean/ajax/CategoryBrowserPluginBean.java | 354 --- .../web/bean/ajax/ContentUpdateBean.java | 151 - .../web/bean/ajax/FileUploadBean.java | 254 -- .../alfresco/web/bean/ajax/MySpacesBean.java | 110 - .../web/bean/ajax/NavigatorPluginBean.java | 749 ----- .../alfresco/web/bean/ajax/NodeInfoBean.java | 185 -- .../alfresco/web/bean/ajax/PickerBean.java | 563 ---- .../web/bean/ajax/PortletActionsBean.java | 124 - .../web/bean/ajax/PresenceProxyBean.java | 115 - .../alfresco/web/bean/ajax/TaskInfoBean.java | 169 -- .../web/bean/categories/CategoriesDialog.java | 705 ----- .../bean/categories/CreateCategoryDialog.java | 191 -- .../bean/categories/DeleteCategoryDialog.java | 420 --- .../bean/categories/EditCategoryDialog.java | 332 --- .../categories/EditNodeCategoriesDialog.java | 184 -- .../bean/clipboard/AbstractClipboardItem.java | 218 -- .../web/bean/clipboard/ClipboardBean.java | 371 --- .../web/bean/clipboard/ClipboardItem.java | 96 - .../web/bean/clipboard/ClipboardStatus.java | 33 - .../clipboard/WorkspaceClipboardItem.java | 344 --- .../web/bean/coci/CCCheckinFileDialog.java | 72 - .../web/bean/coci/CCCheckoutFileDialog.java | 200 -- .../bean/coci/CCCheckoutFileLinkDialog.java | 115 - .../web/bean/coci/CCEditFileDialog.java | 69 - .../web/bean/coci/CCEditHtmlInlineDialog.java | 64 - .../web/bean/coci/CCEditTextInlineDialog.java | 64 - .../alfresco/web/bean/coci/CCProperties.java | 431 --- .../bean/coci/CCUndoCheckoutFileDialog.java | 126 - .../web/bean/coci/CCUpdateFileDialog.java | 72 - .../bean/coci/CCWorkingCopyMissingDialog.java | 71 - .../web/bean/coci/CancelEditingDialog.java | 141 - .../web/bean/coci/CheckinCheckoutDialog.java | 648 ----- .../web/bean/coci/DoneEditingDialog.java | 208 -- .../web/bean/coci/EditOfflineDialog.java | 228 -- .../web/bean/coci/EditOnlineDialog.java | 210 -- .../web/bean/coci/UploadNewVersionDialog.java | 89 - .../web/bean/content/AddContentDialog.java | 355 --- .../web/bean/content/BaseContentWizard.java | 623 ----- .../web/bean/content/CreateContentWizard.java | 285 -- .../DeleteContentAssociationDialog.java | 105 - .../web/bean/content/DeleteContentDialog.java | 180 -- .../bean/content/DocumentDetailsDialog.java | 1023 ------- .../content/DocumentLinkDetailsDialog.java | 224 -- .../content/DocumentPropertiesDialog.java | 452 --- .../content/EditContentPropertiesDialog.java | 331 --- .../web/bean/content/EditContentWizard.java | 86 - .../content/EditSimpleWorkflowDialog.java | 185 -- .../content/InviteContentUsersWizard.java | 68 - .../content/SetContentPropertiesDialog.java | 54 - .../VersionedDocumentDetailsDialog.java | 602 ---- .../content/ViewContentPropertiesDialog.java | 113 - .../web/bean/dashboard/DashboardManager.java | 433 --- .../web/bean/dashboard/DashboardWizard.java | 497 ---- .../bean/dashboard/GettingStartedBean.java | 83 - .../web/bean/dashboard/PageConfig.java | 424 --- .../web/bean/dialog/BaseDialogBean.java | 457 --- .../web/bean/dialog/ChangeViewSupport.java | 47 - .../web/bean/dialog/DialogManager.java | 547 ---- .../alfresco/web/bean/dialog/DialogState.java | 82 - .../web/bean/dialog/FilterViewSupport.java | 47 - .../alfresco/web/bean/dialog/IDialogBean.java | 150 - .../web/bean/dialog/NavigationSupport.java | 45 - .../bean/forums/CreateDiscussionDialog.java | 217 -- .../web/bean/forums/CreateForumDialog.java | 61 - .../web/bean/forums/CreateForumsDialog.java | 61 - .../web/bean/forums/CreatePostDialog.java | 90 - .../web/bean/forums/CreateReplyDialog.java | 90 - .../web/bean/forums/CreateTopicDialog.java | 181 -- .../web/bean/forums/DeleteForumDialog.java | 131 - .../web/bean/forums/DeleteForumsDialog.java | 97 - .../web/bean/forums/DeletePostDialog.java | 71 - .../web/bean/forums/DeleteTopicDialog.java | 109 - .../web/bean/forums/EditPostDialog.java | 112 - .../web/bean/forums/ForumDetailsDialog.java | 206 -- .../alfresco/web/bean/forums/ForumsBean.java | 1351 --------- .../web/bean/forums/ForumsDetailsDialog.java | 206 -- .../web/bean/forums/TopicDetailsDialog.java | 206 -- .../generator/AjaxTagPickerGenerator.java | 108 - .../bean/generator/AssociationGenerator.java | 89 - .../generator/BaseComponentGenerator.java | 780 ------ .../generator/CategorySelectorGenerator.java | 96 - .../generator/CharsetSelectorGenerator.java | 82 - .../web/bean/generator/CheckboxGenerator.java | 85 - .../generator/ChildAssociationGenerator.java | 89 - .../bean/generator/DatePickerGenerator.java | 210 -- .../generator/DateTimePickerGenerator.java | 70 - .../generator/HeaderSeparatorGenerator.java | 47 - .../generator/HtmlSeparatorGenerator.java | 104 - .../bean/generator/IComponentGenerator.java | 75 - .../web/bean/generator/LabelGenerator.java | 60 - .../generator/LabelSeparatorGenerator.java | 110 - .../generator/LanguageSelectorGenerator.java | 112 - .../web/bean/generator/LinkGenerator.java | 100 - .../generator/MimeTypeSelectorGenerator.java | 84 - .../MlContainerLanguageSelectorGenerator.java | 113 - .../MultilingualTextAreaGenerator.java | 62 - .../MultilingualTextFieldGenerator.java | 58 - .../bean/generator/SeparatorGenerator.java | 41 - .../generator/SpaceIconPickerGenerator.java | 106 - .../generator/StoreSelectorGenerator.java | 48 - .../web/bean/generator/TextAreaGenerator.java | 97 - .../bean/generator/TextFieldGenerator.java | 359 --- .../web/bean/groups/AddUsersDialog.java | 342 --- .../web/bean/groups/CreateGroupDialog.java | 178 -- .../web/bean/groups/DeleteGroupDialog.java | 149 - .../web/bean/groups/GroupsDialog.java | 847 ------ .../alfresco/web/bean/jmx/JmxDumperBean.java | 93 - .../web/bean/ml/AddTranslationDialog.java | 175 -- .../AddTranslationWithoutContentDialog.java | 220 -- .../web/bean/ml/EditMLContainerDialog.java | 164 -- .../web/bean/ml/MakeMultilingualDialog.java | 297 -- .../web/bean/ml/MultilingualManageDialog.java | 549 ---- .../web/bean/ml/MultilingualUtils.java | 158 -- .../web/bean/ml/NewEditionWizard.java | 618 ----- .../web/bean/ml/SingleEditionBean.java | 96 - .../web/bean/preview/BasePreviewBean.java | 193 -- .../web/bean/preview/DocumentPreviewBean.java | 151 - .../web/bean/preview/SpacePreviewBean.java | 165 -- .../web/bean/repository/DataDictionary.java | 157 -- .../alfresco/web/bean/repository/MapNode.java | 224 -- .../alfresco/web/bean/repository/Node.java | 526 ---- .../bean/repository/NodePropertyResolver.java | 51 - .../web/bean/repository/Preferences.java | 134 - .../bean/repository/PreferencesService.java | 74 - .../web/bean/repository/QNameNodeMap.java | 153 - .../web/bean/repository/Repository.java | 883 ------ .../web/bean/repository/TransientMapNode.java | 174 -- .../web/bean/repository/TransientNode.java | 313 --- .../alfresco/web/bean/repository/User.java | 328 --- .../admin/RepoAdminConsoleBean.java | 205 -- .../tenant/TenantAdminConsoleBean.java | 205 -- .../bean/rules/CreateCompositeRuleWizard.java | 452 --- .../web/bean/rules/CreateRuleWizard.java | 952 ------- .../web/bean/rules/DeleteRuleDialog.java | 173 -- .../web/bean/rules/EditRuleWizard.java | 259 -- .../alfresco/web/bean/rules/RulesDialog.java | 551 ---- .../rules/handlers/BaseConditionHandler.java | 83 - .../handlers/CompareMimeTypeHandler.java | 90 - .../handlers/CompositeConditionHandler.java | 132 - .../bean/rules/handlers/HasAspectHandler.java | 91 - .../bean/rules/handlers/HasTagHandler.java | 77 - .../rules/handlers/InCategoryHandler.java | 88 - .../bean/rules/handlers/IsSubTypeHandler.java | 91 - .../rules/handlers/PropertyValueHandler.java | 93 - .../DatePropertyValueConditionHandler.java | 94 - .../IntegerPropertyValueConditionHandler.java | 93 - .../TextPropertyValueConditionHandler.java | 145 - .../web/bean/search/AdvancedSearchDialog.java | 1126 -------- .../web/bean/search/EditSearchDialog.java | 122 - .../web/bean/search/SaveSearchDialog.java | 131 - .../web/bean/search/SearchContext.java | 1090 -------- .../web/bean/search/SearchProperties.java | 520 ---- .../bean/spaces/ApplyDocTemplateDialog.java | 112 - .../bean/spaces/ApplyRssTemplateDialog.java | 121 - .../bean/spaces/ApplySpaceTemplateDialog.java | 112 - .../web/bean/spaces/CreateSpaceDialog.java | 65 - .../web/bean/spaces/CreateSpaceWizard.java | 769 ------ .../spaces/DeleteSpaceAssociationDialog.java | 105 - .../web/bean/spaces/DeleteSpaceDialog.java | 345 --- .../bean/spaces/EditSimpleWorkflowDialog.java | 201 -- .../web/bean/spaces/EditSpaceDialog.java | 206 -- .../bean/spaces/InviteSpaceUsersWizard.java | 68 - .../web/bean/spaces/RecentSpacesBean.java | 224 -- .../web/bean/spaces/SpaceDetailsDialog.java | 492 ---- .../TrashcanDeleteAllItemsDialog.java | 94 - .../trashcan/TrashcanDeleteItemDialog.java | 113 - .../TrashcanDeleteListedItemsDialog.java | 103 - .../web/bean/trashcan/TrashcanDialog.java | 906 ------ .../bean/trashcan/TrashcanDialogProperty.java | 315 --- .../trashcan/TrashcanItemDetailsDialog.java | 94 - .../trashcan/TrashcanRecoverItemDialog.java | 175 -- .../TrashcanRecoverListedItemsDialog.java | 110 - .../TrashcanRecoveryReportDialog.java | 57 - .../bean/users/ChangeMyPasswordDialog.java | 95 - .../web/bean/users/ChangePasswordDialog.java | 95 - .../web/bean/users/ContentUsersBean.java | 90 - .../web/bean/users/CreateUserWizard.java | 1007 ------- .../web/bean/users/DeleteUserDialog.java | 304 -- .../users/EditContentUserRolesDialog.java | 82 - .../web/bean/users/EditFileDialog.java | 44 - .../web/bean/users/EditUserDetailsDialog.java | 218 -- .../web/bean/users/EditUserRolesDialog.java | 87 - .../web/bean/users/EditUserWizard.java | 178 -- .../web/bean/users/EmailSpaceUsersDialog.java | 629 ----- .../users/MailInviteSpaceUsersWizard.java | 46 - .../bean/users/RemoveContentUserDialog.java | 101 - .../bean/users/RemoveInvitedUserDialog.java | 105 - .../web/bean/users/SpaceUsersBean.java | 90 - .../web/bean/users/UserConsoleDialog.java | 50 - .../web/bean/users/UserMembersBean.java | 959 ------- .../web/bean/users/UserPreferencesBean.java | 419 --- .../web/bean/users/UserProfileDialog.java | 72 - .../web/bean/users/UserShortcutsBean.java | 447 --- .../web/bean/users/UsersBeanProperties.java | 495 ---- .../alfresco/web/bean/users/UsersDialog.java | 506 ---- .../web/bean/wizard/AbstractWizardBean.java | 359 --- .../bean/wizard/BaseInviteUsersWizard.java | 909 ------ .../web/bean/wizard/BaseWizardBean.java | 142 - .../alfresco/web/bean/wizard/IWizardBean.java | 89 - .../web/bean/wizard/NewUserWizard.java | 1094 -------- .../web/bean/wizard/WizardManager.java | 670 ----- .../alfresco/web/bean/wizard/WizardState.java | 141 - .../web/bean/workflow/BaseReassignDialog.java | 203 -- .../bean/workflow/CancelWorkflowDialog.java | 190 -- .../web/bean/workflow/ManageTaskDialog.java | 921 ------- .../web/bean/workflow/ReassignTaskDialog.java | 114 - .../bean/workflow/ReassignWorkItemDialog.java | 114 - .../bean/workflow/StartWorkflowWizard.java | 816 ------ .../workflow/ViewCompletedTaskDialog.java | 75 - .../web/bean/workflow/WorkflowBean.java | 388 --- .../bean/workflow/WorkflowConsoleBean.java | 209 -- .../web/bean/workflow/WorkflowTaskNode.java | 159 -- .../web/bean/workflow/WorkflowUtil.java | 302 -- .../web/config/ActionsConfigElement.java | 344 --- .../web/config/ActionsElementReader.java | 279 -- .../config/AdvancedSearchConfigElement.java | 255 -- .../config/AdvancedSearchElementReader.java | 133 - .../alfresco/web/config/AspectEvaluator.java | 63 - .../web/config/ClientConfigElement.java | 942 ------- .../web/config/ClientElementReader.java | 373 --- .../config/CommandServletConfigElement.java | 114 - .../config/CommandServletElementReader.java | 82 - .../web/config/ConfigAdminInterpreter.java | 163 -- .../web/config/DashboardsConfigElement.java | 211 -- .../web/config/DashboardsElementReader.java | 236 -- .../web/config/DialogsConfigElement.java | 620 ----- .../web/config/DialogsElementReader.java | 211 -- .../web/config/LanguagesConfigElement.java | 134 - .../web/config/LanguagesElementReader.java | 83 - .../web/config/NavigationConfigElement.java | 255 -- .../web/config/NavigationElementReader.java | 89 - .../alfresco/web/config/NavigationResult.java | 96 - .../web/config/NodeTypeEvaluator.java | 61 - .../alfresco/web/config/PathEvaluator.java | 61 - .../config/PropertySheetConfigElement.java | 466 ---- .../config/PropertySheetElementReader.java | 119 - .../web/config/SidebarConfigElement.java | 255 -- .../web/config/SidebarElementReader.java | 112 - .../web/config/ViewsConfigElement.java | 378 --- .../web/config/ViewsElementReader.java | 159 -- .../web/config/WebClientConfigBootstrap.java | 142 - .../web/config/WizardsConfigElement.java | 483 ---- .../web/config/WizardsElementReader.java | 184 -- .../alfresco/web/data/DynamicResolver.java | 36 - .../org/alfresco/web/data/IDataContainer.java | 99 - .../java/org/alfresco/web/data/MergeSort.java | 123 - .../java/org/alfresco/web/data/QuickSort.java | 182 -- .../main/java/org/alfresco/web/data/Sort.java | 483 ---- .../auth/AbstractAuthenticationHandler.java | 94 - .../auth/BasicAuthenticationHandler.java | 210 -- .../KerberosAuthenticationHandler.java | 93 - .../auth/ntlm/NtlmAuthenticationHandler.java | 93 - .../web/ui/common/ComponentConstants.java | 55 - .../alfresco/web/ui/common/NodeListUtils.java | 107 - .../web/ui/common/NodePropertyComparator.java | 125 - .../web/ui/common/PanelGenerator.java | 344 --- .../web/ui/common/ReportedException.java | 66 - .../web/ui/common/SortableSelectItem.java | 65 - .../org/alfresco/web/ui/common/Utils.java | 1253 --------- .../alfresco/web/ui/common/WebResources.java | 57 - .../common/component/IBreadcrumbHandler.java | 51 - .../web/ui/common/component/UIActionLink.java | 362 --- .../web/ui/common/component/UIBreadcrumb.java | 318 --- .../ui/common/component/UIGenericPicker.java | 729 ----- .../ui/common/component/UIImagePicker.java | 75 - .../web/ui/common/component/UIListItem.java | 259 -- .../web/ui/common/component/UIListItems.java | 121 - .../web/ui/common/component/UIMenu.java | 225 -- .../web/ui/common/component/UIModeList.java | 337 --- .../web/ui/common/component/UIOutputText.java | 175 -- .../web/ui/common/component/UIPanel.java | 656 ----- .../web/ui/common/component/UISelectList.java | 668 ----- .../ui/common/component/UIStatusMessage.java | 354 --- .../web/ui/common/component/UploadInput.java | 98 - .../component/data/GridArrayDataModel.java | 77 - .../component/data/GridListDataModel.java | 90 - .../common/component/data/IGridDataModel.java | 59 - .../ui/common/component/data/UIColumn.java | 166 -- .../ui/common/component/data/UIDataPager.java | 658 ----- .../ui/common/component/data/UIRichList.java | 589 ---- .../ui/common/component/data/UISortLink.java | 352 --- .../component/debug/BaseDebugComponent.java | 173 -- .../debug/UIHttpApplicationState.java | 54 - .../component/debug/UIHttpRequestHeaders.java | 54 - .../component/debug/UIHttpRequestParams.java | 54 - .../component/debug/UIHttpRequestState.java | 54 - .../component/debug/UIHttpSessionState.java | 54 - .../debug/UIRepositoryProperties.java | 98 - .../component/debug/UISystemProperties.java | 79 - .../component/description/UIDescription.java | 137 - .../component/description/UIDescriptions.java | 97 - .../description/UIDynamicDescription.java | 276 -- .../component/evaluator/BaseEvaluator.java | 145 - .../component/evaluator/BooleanEvaluator.java | 64 - .../evaluator/StringEqualsEvaluator.java | 113 - .../evaluator/ValueSetEvaluator.java | 45 - .../converter/BooleanLabelConverter.java | 102 - .../common/converter/ByteSizeConverter.java | 118 - .../common/converter/MultiValueConverter.java | 97 - .../ui/common/converter/XMLDateConverter.java | 122 - .../common/renderer/ActionLinkRenderer.java | 445 --- .../web/ui/common/renderer/BaseRenderer.java | 113 - .../common/renderer/BreadcrumbRenderer.java | 171 -- .../common/renderer/DatePickerRenderer.java | 465 ---- .../ui/common/renderer/ErrorsRenderer.java | 202 -- .../ImagePickerRadioPanelRenderer.java | 80 - .../renderer/ImagePickerRadioRenderer.java | 351 --- .../ui/common/renderer/ModeListRenderer.java | 438 --- .../renderer/data/IRichListRenderer.java | 91 - .../renderer/data/RichListRenderer.java | 705 ----- .../web/ui/common/tag/ActionLinkTag.java | 229 -- .../common/tag/BooleanLabelConverterTag.java | 56 - .../web/ui/common/tag/BreadcrumbTag.java | 160 -- .../ui/common/tag/ByteSizeConverterTag.java | 54 - .../alfresco/web/ui/common/tag/ErrorsTag.java | 87 - .../web/ui/common/tag/GenericPickerTag.java | 281 -- .../web/ui/common/tag/HtmlComponentTag.java | 102 - .../common/tag/ImagePickerRadioPanelTag.java | 96 - .../ui/common/tag/ImagePickerRadioTag.java | 257 -- .../web/ui/common/tag/InputDatePickerTag.java | 172 -- .../web/ui/common/tag/ListItemTag.java | 159 -- .../web/ui/common/tag/ListItemsTag.java | 101 - .../alfresco/web/ui/common/tag/MenuTag.java | 143 - .../web/ui/common/tag/ModeListTag.java | 426 --- .../ui/common/tag/MultiValueConverterTag.java | 56 - .../web/ui/common/tag/OutputTextTag.java | 96 - .../alfresco/web/ui/common/tag/PanelTag.java | 257 -- .../web/ui/common/tag/SelectListTag.java | 201 -- .../web/ui/common/tag/StatusMessageTag.java | 97 - .../web/ui/common/tag/UploadInputTag.java | 87 - .../ui/common/tag/XMLDateConverterTag.java | 45 - .../web/ui/common/tag/data/ColumnTag.java | 151 - .../web/ui/common/tag/data/DataPagerTag.java | 90 - .../web/ui/common/tag/data/RichListTag.java | 290 -- .../web/ui/common/tag/data/SortLinkTag.java | 117 - .../web/ui/common/tag/debug/BaseDebugTag.java | 77 - .../tag/debug/HttpApplicationStateTag.java | 44 - .../tag/debug/HttpRequestHeadersTag.java | 44 - .../tag/debug/HttpRequestParamsTag.java | 44 - .../common/tag/debug/HttpRequestStateTag.java | 44 - .../common/tag/debug/HttpSessionStateTag.java | 44 - .../tag/debug/RepositoryPropertiesTag.java | 43 - .../common/tag/debug/SystemPropertiesTag.java | 44 - .../tag/description/DescriptionTag.java | 95 - .../tag/description/DescriptionsTag.java | 84 - .../description/DynamicDescriptionTag.java | 95 - .../tag/evaluator/BooleanEvaluatorTag.java | 40 - .../tag/evaluator/GenericEvaluatorTag.java | 76 - .../evaluator/StringEqualsEvaluatorTag.java | 74 - .../tag/evaluator/ValueSetEvaluatorTag.java | 40 - .../alfresco/web/ui/repo/RepoConstants.java | 77 - .../alfresco/web/ui/repo/WebResources.java | 48 - .../repo/component/AbstractItemSelector.java | 836 ------ .../ui/repo/component/BaseAjaxItemPicker.java | 591 ---- .../component/IRepoBreadcrumbHandler.java | 42 - .../web/ui/repo/component/UIActions.java | 704 ----- .../repo/component/UIAjaxCategoryPicker.java | 52 - .../ui/repo/component/UIAjaxFilePicker.java | 124 - .../ui/repo/component/UIAjaxFolderPicker.java | 53 - .../ui/repo/component/UIAjaxTagPicker.java | 321 --- .../ui/repo/component/UICategoryBrowser.java | 254 -- .../ui/repo/component/UICategorySelector.java | 142 - .../ui/repo/component/UICharsetSelector.java | 102 - .../ui/repo/component/UIContentSelector.java | 427 --- .../ui/repo/component/UIDialogButtons.java | 320 --- .../ui/repo/component/UILanguageSelector.java | 145 - .../web/ui/repo/component/UILockIcon.java | 409 --- .../ui/repo/component/UIMimeTypeSelector.java | 101 - .../ui/repo/component/UIMultiValueEditor.java | 419 --- .../web/ui/repo/component/UINavigator.java | 452 --- .../ui/repo/component/UINodeDescendants.java | 185 -- .../web/ui/repo/component/UINodeInfo.java | 158 -- .../web/ui/repo/component/UINodePath.java | 79 - .../ui/repo/component/UINodeWorkflowInfo.java | 372 --- .../web/ui/repo/component/UIOpenSearch.java | 365 --- .../component/UISearchCustomProperties.java | 479 ---- .../web/ui/repo/component/UISidebar.java | 286 -- .../web/ui/repo/component/UISimpleSearch.java | 341 --- .../ui/repo/component/UISpaceSelector.java | 141 - .../ui/repo/component/UIStoreSelector.java | 88 - .../web/ui/repo/component/UITagSelector.java | 67 - .../web/ui/repo/component/UITree.java | 418 --- .../ui/repo/component/UIUserGroupPicker.java | 248 -- .../ui/repo/component/UIWorkflowHistory.java | 283 -- .../ui/repo/component/UIWorkflowSummary.java | 207 -- .../evaluator/ActionInstanceEvaluator.java | 221 -- .../evaluator/PermissionEvaluator.java | 223 -- .../property/BaseAssociationEditor.java | 1213 -------- .../component/property/PropertySheetItem.java | 327 --- .../component/property/UIAssociation.java | 143 - .../property/UIAssociationEditor.java | 306 -- .../property/UIChildAssociation.java | 143 - .../property/UIChildAssociationEditor.java | 275 -- .../repo/component/property/UIProperty.java | 233 -- .../component/property/UIPropertySheet.java | 908 ------ .../repo/component/property/UISeparator.java | 89 - .../component/shelf/UIClipboardShelfItem.java | 438 --- .../shelf/UIRecentSpacesShelfItem.java | 305 -- .../web/ui/repo/component/shelf/UIShelf.java | 500 ---- .../ui/repo/component/shelf/UIShelfGroup.java | 171 -- .../ui/repo/component/shelf/UIShelfItem.java | 49 - .../component/shelf/UIShortcutsShelfItem.java | 392 --- .../template/DefaultModelHelper.java | 113 - .../repo/component/template/UITemplate.java | 327 --- .../ui/repo/converter/CharsetConverter.java | 75 - .../repo/converter/DisplayPathConverter.java | 100 - .../ui/repo/converter/LanguageConverter.java | 87 - .../ui/repo/converter/MimeTypeConverter.java | 74 - .../repo/renderer/BaseMultiValueRenderer.java | 351 --- .../renderer/MultiValueFieldRenderer.java | 80 - .../renderer/MultiValueSelectorRenderer.java | 93 - .../MultilingualTextAreaRenderer.java | 77 - .../renderer/MultilingualTextRenderer.java | 61 - .../renderer/NodeDescendantsLinkRenderer.java | 296 -- .../repo/renderer/NodePathLinkRenderer.java | 383 --- .../ui/repo/renderer/YahooTreeRenderer.java | 220 -- .../property/AssociationRenderer.java | 35 - .../property/ChildAssociationRenderer.java | 35 - .../renderer/property/PropertyRenderer.java | 35 - .../property/PropertySheetItemRenderer.java | 131 - .../renderer/property/SeparatorRenderer.java | 99 - .../alfresco/web/ui/repo/tag/ActionsTag.java | 130 - .../ui/repo/tag/AjaxCategorySelectorTag.java | 44 - .../web/ui/repo/tag/AjaxFileSelectorTag.java | 78 - .../ui/repo/tag/AjaxFolderSelectorTag.java | 44 - .../web/ui/repo/tag/AjaxItemSelectorTag.java | 163 -- .../web/ui/repo/tag/AjaxTagSelectorTag.java | 44 - .../web/ui/repo/tag/BaseMultiValueTag.java | 142 - .../web/ui/repo/tag/CategoryBrowserTag.java | 63 - .../web/ui/repo/tag/CategorySelectorTag.java | 43 - .../web/ui/repo/tag/CharsetSelectorTag.java | 97 - .../web/ui/repo/tag/ContentSelectorTag.java | 122 - .../web/ui/repo/tag/DialogButtonsTag.java | 52 - .../web/ui/repo/tag/ItemSelectorTag.java | 178 -- .../web/ui/repo/tag/LanguageSelectorTag.java | 155 -- .../web/ui/repo/tag/LoadBundleTag.java | 197 -- .../alfresco/web/ui/repo/tag/LockIconTag.java | 189 -- .../web/ui/repo/tag/MimeTypeSelectorTag.java | 96 - .../web/ui/repo/tag/MultiValueFieldTag.java | 46 - .../ui/repo/tag/MultiValueSelectorTag.java | 45 - .../web/ui/repo/tag/NavigatorTag.java | 86 - .../web/ui/repo/tag/NodeDescendantsTag.java | 162 -- .../alfresco/web/ui/repo/tag/NodeInfoTag.java | 86 - .../alfresco/web/ui/repo/tag/NodePathTag.java | 164 -- .../web/ui/repo/tag/NodeWorkflowInfoTag.java | 86 - .../web/ui/repo/tag/OpenSearchTag.java | 52 - .../org/alfresco/web/ui/repo/tag/PageTag.java | 390 --- .../repo/tag/SearchCustomPropertiesTag.java | 102 - .../alfresco/web/ui/repo/tag/SidebarTag.java | 87 - .../web/ui/repo/tag/SimpleSearchTag.java | 103 - .../web/ui/repo/tag/SpaceSelectorTag.java | 44 - .../web/ui/repo/tag/SystemErrorTag.java | 359 --- .../alfresco/web/ui/repo/tag/TemplateTag.java | 117 - .../web/ui/repo/tag/UploadFormTag.java | 100 - .../web/ui/repo/tag/UserGroupPickerTag.java | 99 - .../repo/tag/WebProjectFolderSelectorTag.java | 43 - .../web/ui/repo/tag/WorkflowHistoryTag.java | 85 - .../web/ui/repo/tag/WorkflowSummaryTag.java | 86 - .../web/ui/repo/tag/YahooTreeTag.java | 151 - .../evaluator/ActionInstanceEvaluatorTag.java | 76 - .../tag/evaluator/PermissionEvaluatorTag.java | 91 - .../tag/property/AssociationEditorTag.java | 42 - .../ui/repo/tag/property/AssociationTag.java | 50 - .../property/BaseAssociationEditorTag.java | 166 -- .../property/ChildAssociationEditorTag.java | 42 - .../tag/property/ChildAssociationTag.java | 50 - .../tag/property/PropertySheetGridTag.java | 216 -- .../tag/property/PropertySheetItemTag.java | 112 - .../web/ui/repo/tag/property/PropertyTag.java | 126 - .../repo/tag/shelf/ClipboardShelfItemTag.java | 113 - .../tag/shelf/RecentSpacesShelfItemTag.java | 112 - .../web/ui/repo/tag/shelf/ShelfGroupTag.java | 102 - .../web/ui/repo/tag/shelf/ShelfItemTag.java | 51 - .../web/ui/repo/tag/shelf/ShelfTag.java | 191 -- .../repo/tag/shelf/ShortcutsShelfItemTag.java | 135 - .../alfrescoNtlm/ntlm-filter-context.xml | 158 -- .../alfrescoNtlm/ntlm-filter.properties | 4 - .../external/external-filter-context.xml | 30 - .../kerberos/kerberos-filter-context.xml | 194 -- .../kerberos/kerberos-filter.properties | 6 - .../passthru/ntlm-filter-context.xml | 161 -- .../passthru/ntlm-filter.properties | 4 - .../web-client-application-context.xml | 43 +- war/src/main/webapp/WEB-INF/web.xml | 55 - 634 files changed, 1 insertion(+), 133804 deletions(-) delete mode 100644 war/src/main/java/org/alfresco/repo/web/scripts/portlet/WebClientPortletAuthenticatorFactory.java delete mode 100644 war/src/main/java/org/alfresco/repo/web/scripts/portlet/WebScriptRepoPortlet.java delete mode 100644 war/src/main/java/org/alfresco/repo/web/scripts/servlet/AuthenticatorServlet.java delete mode 100644 war/src/main/java/org/alfresco/repo/web/scripts/servlet/WebClientAuthenticatorFactory.java delete mode 100644 war/src/main/java/org/alfresco/web/action/ActionEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/AddTranslationEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/ApproveDocEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/ApproveNonDraftDocEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/BaseActionEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/CancelCheckoutDocEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/CancelEditingDocEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/CancelWorkflowEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/CheckinDocEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/CheckoutDocEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/CreateForumMLNodeEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/CreateForumNodeEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/CutNodeEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/DeleteDocEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/DiscussNodeEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/DiscussionCopyEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/DiscussionCutEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/DoneEditingDocEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/EditDocCIFSEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/EditDocHttpEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/EditDocOfflineEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/EditDocOnlineCIFSEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/EditDocOnlineHttpEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/EditDocOnlineWebDavEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/EditDocWebDavEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/EditPostEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/ForumsCheckinDocEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/GroupActionEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/MakeMultilingualEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/MultilingualDetailsEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/NewEditionEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/RejectDocEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/RejectNonDraftDocEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/ShortcutNodeEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/StartWorkflowEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/TakeOwnershipDocEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/UnlockDocEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/UnlockedDocEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/UpdateDocEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/action/evaluator/UploadNewVersionEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/app/AlfrescoNavigationHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/app/Application.java delete mode 100644 war/src/main/java/org/alfresco/web/app/ContextListener.java delete mode 100644 war/src/main/java/org/alfresco/web/app/DebugPhaseListener.java delete mode 100644 war/src/main/java/org/alfresco/web/app/ResourceBundleBootstrap.java delete mode 100644 war/src/main/java/org/alfresco/web/app/ResourceBundleWrapper.java delete mode 100644 war/src/main/java/org/alfresco/web/app/context/IContextListener.java delete mode 100644 war/src/main/java/org/alfresco/web/app/context/UIContextService.java delete mode 100644 war/src/main/java/org/alfresco/web/app/portlet/AlfrescoDefaultViewSelector.java delete mode 100644 war/src/main/java/org/alfresco/web/app/portlet/AlfrescoFacesPortlet.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/AbstractAuthenticationFilter.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/AcceptLanguage.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/AdminAuthenticationFilter.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/AlfrescoX509ServletFilter.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/AuthenticationFilter.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/AuthenticationHelper.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/AuthenticationStatus.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/BaseDownloadContentServlet.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/BaseServlet.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/BaseTemplateContentServlet.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/CmisSecurityContextCleanerFilter.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/CommandServlet.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/DownloadContentServlet.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/DownloadRawContentServlet.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/ExternalAccessServlet.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/FacesHelper.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/GlobalLocalizationFilter.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/GuestDownloadContentServlet.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/GuestTemplateContentServlet.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/HTTPRequestAuthenticationFilter.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/KerberosAuthenticationFilter.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/ModeDetectionFilter.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/NTLMAuthenticationFilter.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/SecurityContextCleanupPhaseListener.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/TemplateContentServlet.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/UploadContentServlet.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/UploadFileServlet.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/WebScriptSSOAuthenticationFilter.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/WebscriptCookieAuthenticationFilter.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/WorkflowDefinitionImageServlet.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/ajax/AjaxCommand.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/ajax/AjaxServlet.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/ajax/BaseAjaxCommand.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/ajax/GetCommand.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/ajax/InvokeCommand.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/command/ApproveWorkflowCommand.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/command/BaseNodeCommandProcessor.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/command/BaseUIActionCommand.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/command/Command.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/command/CommandFactory.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/command/CommandProcessor.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/command/EditContentPropertiesCommand.java delete mode 100755 war/src/main/java/org/alfresco/web/app/servlet/command/EditSpaceCommand.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/command/EndTaskCommand.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/command/ExecuteScriptCommand.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/command/ExtCommandProcessor.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/command/ManageTaskDialogCommand.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/command/RejectWorkflowCommand.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/command/ScriptCommandProcessor.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/command/TaskCommandProcessor.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/command/UIActionCommandProcessor.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/command/UserProfileDialogCommand.java delete mode 100644 war/src/main/java/org/alfresco/web/app/servlet/command/WorkflowCommandProcessor.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/AboutBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/BaseDetailsBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/BrowseBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/CategoriesProperties.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/CategoryBrowserBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/ErrorBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/FileUploadBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/LinkPropertiesDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/LoginBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/LoginOutcomeBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/MultiValueEditorBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/NavigationBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/NodeEventListener.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/SidebarBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/SpaceLinkDetailsDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/TemplateMailHelperBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/TemplateSupportBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/actions/BaseActionWizard.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/actions/IHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/actions/RunActionWizard.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/actions/handlers/AddFeaturesHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/actions/handlers/BaseActionHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/actions/handlers/CheckInHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/actions/handlers/CheckOutHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/actions/handlers/CopyHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/actions/handlers/ImportHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/actions/handlers/LinkCategoryHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/actions/handlers/MailHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/actions/handlers/MoveHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/actions/handlers/RemoveFeaturesHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/actions/handlers/ScriptHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/actions/handlers/SimpleWorkflowHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/actions/handlers/SpecialiseTypeHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/actions/handlers/TransformHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/actions/handlers/TransformImageHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/admin/AdminConsoleDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/admin/AdminNodeBrowseBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/admin/ConfigAdminConsoleBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/admin/ExportDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/admin/ImportDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/admin/ShowSystemInfoDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/ajax/CategoryBrowserPluginBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/ajax/ContentUpdateBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/ajax/FileUploadBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/ajax/MySpacesBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/ajax/NavigatorPluginBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/ajax/NodeInfoBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/ajax/PickerBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/ajax/PortletActionsBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/ajax/PresenceProxyBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/ajax/TaskInfoBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/categories/CategoriesDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/categories/CreateCategoryDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/categories/DeleteCategoryDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/categories/EditCategoryDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/categories/EditNodeCategoriesDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/clipboard/AbstractClipboardItem.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/clipboard/ClipboardBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/clipboard/ClipboardItem.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/clipboard/ClipboardStatus.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/clipboard/WorkspaceClipboardItem.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/coci/CCCheckinFileDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/coci/CCCheckoutFileDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/coci/CCCheckoutFileLinkDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/coci/CCEditFileDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/coci/CCEditHtmlInlineDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/coci/CCEditTextInlineDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/coci/CCProperties.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/coci/CCUndoCheckoutFileDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/coci/CCUpdateFileDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/coci/CCWorkingCopyMissingDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/coci/CancelEditingDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/coci/CheckinCheckoutDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/coci/DoneEditingDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/coci/EditOfflineDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/coci/EditOnlineDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/coci/UploadNewVersionDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/content/AddContentDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/content/BaseContentWizard.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/content/CreateContentWizard.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/content/DeleteContentAssociationDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/content/DeleteContentDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/content/DocumentDetailsDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/content/DocumentLinkDetailsDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/content/DocumentPropertiesDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/content/EditContentPropertiesDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/content/EditContentWizard.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/content/EditSimpleWorkflowDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/content/InviteContentUsersWizard.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/content/SetContentPropertiesDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/content/VersionedDocumentDetailsDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/content/ViewContentPropertiesDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/dashboard/DashboardManager.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/dashboard/DashboardWizard.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/dashboard/GettingStartedBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/dashboard/PageConfig.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/dialog/BaseDialogBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/dialog/ChangeViewSupport.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/dialog/DialogManager.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/dialog/DialogState.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/dialog/FilterViewSupport.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/dialog/IDialogBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/dialog/NavigationSupport.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/forums/CreateDiscussionDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/forums/CreateForumDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/forums/CreateForumsDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/forums/CreatePostDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/forums/CreateReplyDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/forums/CreateTopicDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/forums/DeleteForumDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/forums/DeleteForumsDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/forums/DeletePostDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/forums/DeleteTopicDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/forums/EditPostDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/forums/ForumDetailsDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/forums/ForumsBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/forums/ForumsDetailsDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/forums/TopicDetailsDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/AjaxTagPickerGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/AssociationGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/BaseComponentGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/CategorySelectorGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/CharsetSelectorGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/CheckboxGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/ChildAssociationGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/DatePickerGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/DateTimePickerGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/HeaderSeparatorGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/HtmlSeparatorGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/IComponentGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/LabelGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/LabelSeparatorGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/LanguageSelectorGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/LinkGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/MimeTypeSelectorGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/MlContainerLanguageSelectorGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/MultilingualTextAreaGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/MultilingualTextFieldGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/SeparatorGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/SpaceIconPickerGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/StoreSelectorGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/TextAreaGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/generator/TextFieldGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/groups/AddUsersDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/groups/CreateGroupDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/groups/DeleteGroupDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/groups/GroupsDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/jmx/JmxDumperBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/ml/AddTranslationDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/ml/AddTranslationWithoutContentDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/ml/EditMLContainerDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/ml/MakeMultilingualDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/ml/MultilingualManageDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/ml/MultilingualUtils.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/ml/NewEditionWizard.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/ml/SingleEditionBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/preview/BasePreviewBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/preview/DocumentPreviewBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/preview/SpacePreviewBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/repository/DataDictionary.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/repository/MapNode.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/repository/Node.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/repository/NodePropertyResolver.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/repository/Preferences.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/repository/PreferencesService.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/repository/QNameNodeMap.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/repository/Repository.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/repository/TransientMapNode.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/repository/TransientNode.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/repository/User.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/repository/admin/RepoAdminConsoleBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/repository/tenant/TenantAdminConsoleBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/rules/CreateCompositeRuleWizard.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/rules/CreateRuleWizard.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/rules/DeleteRuleDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/rules/EditRuleWizard.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/rules/RulesDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/rules/handlers/BaseConditionHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/rules/handlers/CompareMimeTypeHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/rules/handlers/CompositeConditionHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/rules/handlers/HasAspectHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/rules/handlers/HasTagHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/rules/handlers/InCategoryHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/rules/handlers/IsSubTypeHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/rules/handlers/PropertyValueHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/rules/handlers/property/DatePropertyValueConditionHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/rules/handlers/property/IntegerPropertyValueConditionHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/rules/handlers/property/TextPropertyValueConditionHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/search/AdvancedSearchDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/search/EditSearchDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/search/SaveSearchDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/search/SearchContext.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/search/SearchProperties.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/spaces/ApplyDocTemplateDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/spaces/ApplyRssTemplateDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/spaces/ApplySpaceTemplateDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/spaces/CreateSpaceDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/spaces/CreateSpaceWizard.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/spaces/DeleteSpaceAssociationDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/spaces/DeleteSpaceDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/spaces/EditSimpleWorkflowDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/spaces/EditSpaceDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/spaces/InviteSpaceUsersWizard.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/spaces/RecentSpacesBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/spaces/SpaceDetailsDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanDeleteAllItemsDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanDeleteItemDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanDeleteListedItemsDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanDialogProperty.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanItemDetailsDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanRecoverItemDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanRecoverListedItemsDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanRecoveryReportDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/ChangeMyPasswordDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/ChangePasswordDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/ContentUsersBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/CreateUserWizard.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/DeleteUserDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/EditContentUserRolesDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/EditFileDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/EditUserDetailsDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/EditUserRolesDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/EditUserWizard.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/EmailSpaceUsersDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/MailInviteSpaceUsersWizard.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/RemoveContentUserDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/RemoveInvitedUserDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/SpaceUsersBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/UserConsoleDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/UserMembersBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/UserPreferencesBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/UserProfileDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/UserShortcutsBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/UsersBeanProperties.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/users/UsersDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/wizard/AbstractWizardBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/wizard/BaseInviteUsersWizard.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/wizard/BaseWizardBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/wizard/IWizardBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/wizard/NewUserWizard.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/wizard/WizardManager.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/wizard/WizardState.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/workflow/BaseReassignDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/workflow/CancelWorkflowDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/workflow/ManageTaskDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/workflow/ReassignTaskDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/workflow/ReassignWorkItemDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/workflow/StartWorkflowWizard.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/workflow/ViewCompletedTaskDialog.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/workflow/WorkflowBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/workflow/WorkflowConsoleBean.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/workflow/WorkflowTaskNode.java delete mode 100644 war/src/main/java/org/alfresco/web/bean/workflow/WorkflowUtil.java delete mode 100644 war/src/main/java/org/alfresco/web/config/ActionsConfigElement.java delete mode 100644 war/src/main/java/org/alfresco/web/config/ActionsElementReader.java delete mode 100644 war/src/main/java/org/alfresco/web/config/AdvancedSearchConfigElement.java delete mode 100644 war/src/main/java/org/alfresco/web/config/AdvancedSearchElementReader.java delete mode 100644 war/src/main/java/org/alfresco/web/config/AspectEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/config/ClientConfigElement.java delete mode 100644 war/src/main/java/org/alfresco/web/config/ClientElementReader.java delete mode 100644 war/src/main/java/org/alfresco/web/config/CommandServletConfigElement.java delete mode 100644 war/src/main/java/org/alfresco/web/config/CommandServletElementReader.java delete mode 100644 war/src/main/java/org/alfresco/web/config/ConfigAdminInterpreter.java delete mode 100644 war/src/main/java/org/alfresco/web/config/DashboardsConfigElement.java delete mode 100644 war/src/main/java/org/alfresco/web/config/DashboardsElementReader.java delete mode 100644 war/src/main/java/org/alfresco/web/config/DialogsConfigElement.java delete mode 100644 war/src/main/java/org/alfresco/web/config/DialogsElementReader.java delete mode 100644 war/src/main/java/org/alfresco/web/config/LanguagesConfigElement.java delete mode 100644 war/src/main/java/org/alfresco/web/config/LanguagesElementReader.java delete mode 100644 war/src/main/java/org/alfresco/web/config/NavigationConfigElement.java delete mode 100644 war/src/main/java/org/alfresco/web/config/NavigationElementReader.java delete mode 100644 war/src/main/java/org/alfresco/web/config/NavigationResult.java delete mode 100644 war/src/main/java/org/alfresco/web/config/NodeTypeEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/config/PathEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/config/PropertySheetConfigElement.java delete mode 100644 war/src/main/java/org/alfresco/web/config/PropertySheetElementReader.java delete mode 100644 war/src/main/java/org/alfresco/web/config/SidebarConfigElement.java delete mode 100644 war/src/main/java/org/alfresco/web/config/SidebarElementReader.java delete mode 100644 war/src/main/java/org/alfresco/web/config/ViewsConfigElement.java delete mode 100644 war/src/main/java/org/alfresco/web/config/ViewsElementReader.java delete mode 100644 war/src/main/java/org/alfresco/web/config/WebClientConfigBootstrap.java delete mode 100644 war/src/main/java/org/alfresco/web/config/WizardsConfigElement.java delete mode 100644 war/src/main/java/org/alfresco/web/config/WizardsElementReader.java delete mode 100644 war/src/main/java/org/alfresco/web/data/DynamicResolver.java delete mode 100644 war/src/main/java/org/alfresco/web/data/IDataContainer.java delete mode 100644 war/src/main/java/org/alfresco/web/data/MergeSort.java delete mode 100644 war/src/main/java/org/alfresco/web/data/QuickSort.java delete mode 100644 war/src/main/java/org/alfresco/web/data/Sort.java delete mode 100644 war/src/main/java/org/alfresco/web/sharepoint/auth/AbstractAuthenticationHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/sharepoint/auth/BasicAuthenticationHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/sharepoint/auth/kerberos/KerberosAuthenticationHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/sharepoint/auth/ntlm/NtlmAuthenticationHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/ComponentConstants.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/NodeListUtils.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/NodePropertyComparator.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/PanelGenerator.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/ReportedException.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/SortableSelectItem.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/Utils.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/WebResources.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/IBreadcrumbHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/UIActionLink.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/UIBreadcrumb.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/UIGenericPicker.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/UIImagePicker.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/UIListItem.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/UIListItems.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/UIMenu.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/UIModeList.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/UIOutputText.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/UIPanel.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/UISelectList.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/UIStatusMessage.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/UploadInput.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/data/GridArrayDataModel.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/data/GridListDataModel.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/data/IGridDataModel.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/data/UIColumn.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/data/UIDataPager.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/data/UIRichList.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/data/UISortLink.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/debug/BaseDebugComponent.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/debug/UIHttpApplicationState.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/debug/UIHttpRequestHeaders.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/debug/UIHttpRequestParams.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/debug/UIHttpRequestState.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/debug/UIHttpSessionState.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/debug/UIRepositoryProperties.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/debug/UISystemProperties.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/description/UIDescription.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/description/UIDescriptions.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/description/UIDynamicDescription.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/evaluator/BaseEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/evaluator/BooleanEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/evaluator/StringEqualsEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/component/evaluator/ValueSetEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/converter/BooleanLabelConverter.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/converter/ByteSizeConverter.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/converter/MultiValueConverter.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/converter/XMLDateConverter.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/renderer/ActionLinkRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/renderer/BaseRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/renderer/BreadcrumbRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/renderer/DatePickerRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/renderer/ErrorsRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/renderer/ImagePickerRadioPanelRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/renderer/ImagePickerRadioRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/renderer/ModeListRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/renderer/data/IRichListRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/renderer/data/RichListRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/ActionLinkTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/BooleanLabelConverterTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/BreadcrumbTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/ByteSizeConverterTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/ErrorsTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/GenericPickerTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/HtmlComponentTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/ImagePickerRadioPanelTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/ImagePickerRadioTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/InputDatePickerTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/ListItemTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/ListItemsTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/MenuTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/ModeListTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/MultiValueConverterTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/OutputTextTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/PanelTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/SelectListTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/StatusMessageTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/UploadInputTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/XMLDateConverterTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/data/ColumnTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/data/DataPagerTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/data/RichListTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/data/SortLinkTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/debug/BaseDebugTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/debug/HttpApplicationStateTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/debug/HttpRequestHeadersTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/debug/HttpRequestParamsTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/debug/HttpRequestStateTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/debug/HttpSessionStateTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/debug/RepositoryPropertiesTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/debug/SystemPropertiesTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/description/DescriptionTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/description/DescriptionsTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/description/DynamicDescriptionTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/evaluator/BooleanEvaluatorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/evaluator/GenericEvaluatorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/evaluator/StringEqualsEvaluatorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/common/tag/evaluator/ValueSetEvaluatorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/RepoConstants.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/WebResources.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/AbstractItemSelector.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/BaseAjaxItemPicker.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/IRepoBreadcrumbHandler.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UIActions.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UIAjaxCategoryPicker.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UIAjaxFilePicker.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UIAjaxFolderPicker.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UIAjaxTagPicker.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UICategoryBrowser.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UICategorySelector.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UICharsetSelector.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UIContentSelector.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UIDialogButtons.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UILanguageSelector.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UILockIcon.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UIMimeTypeSelector.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UIMultiValueEditor.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UINavigator.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UINodeDescendants.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UINodeInfo.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UINodePath.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UINodeWorkflowInfo.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UIOpenSearch.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UISearchCustomProperties.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UISidebar.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UISimpleSearch.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UISpaceSelector.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UIStoreSelector.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UITagSelector.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UITree.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UIUserGroupPicker.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UIWorkflowHistory.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/UIWorkflowSummary.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/evaluator/ActionInstanceEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/evaluator/PermissionEvaluator.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/property/BaseAssociationEditor.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/property/PropertySheetItem.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/property/UIAssociation.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/property/UIAssociationEditor.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/property/UIChildAssociation.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/property/UIChildAssociationEditor.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/property/UIProperty.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/property/UIPropertySheet.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/property/UISeparator.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/shelf/UIClipboardShelfItem.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/shelf/UIRecentSpacesShelfItem.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/shelf/UIShelf.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/shelf/UIShelfGroup.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/shelf/UIShelfItem.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/shelf/UIShortcutsShelfItem.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/template/DefaultModelHelper.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/component/template/UITemplate.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/converter/CharsetConverter.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/converter/DisplayPathConverter.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/converter/LanguageConverter.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/converter/MimeTypeConverter.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/renderer/BaseMultiValueRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/renderer/MultiValueFieldRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/renderer/MultiValueSelectorRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/renderer/MultilingualTextAreaRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/renderer/MultilingualTextRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/renderer/NodeDescendantsLinkRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/renderer/NodePathLinkRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/renderer/YahooTreeRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/renderer/property/AssociationRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/renderer/property/ChildAssociationRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/renderer/property/PropertyRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/renderer/property/PropertySheetItemRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/renderer/property/SeparatorRenderer.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/ActionsTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/AjaxCategorySelectorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/AjaxFileSelectorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/AjaxFolderSelectorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/AjaxItemSelectorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/AjaxTagSelectorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/BaseMultiValueTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/CategoryBrowserTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/CategorySelectorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/CharsetSelectorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/ContentSelectorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/DialogButtonsTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/ItemSelectorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/LanguageSelectorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/LoadBundleTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/LockIconTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/MimeTypeSelectorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/MultiValueFieldTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/MultiValueSelectorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/NavigatorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/NodeDescendantsTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/NodeInfoTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/NodePathTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/NodeWorkflowInfoTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/OpenSearchTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/PageTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/SearchCustomPropertiesTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/SidebarTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/SimpleSearchTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/SpaceSelectorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/SystemErrorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/TemplateTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/UploadFormTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/UserGroupPickerTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/WebProjectFolderSelectorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/WorkflowHistoryTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/WorkflowSummaryTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/YahooTreeTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/evaluator/ActionInstanceEvaluatorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/evaluator/PermissionEvaluatorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/property/AssociationEditorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/property/AssociationTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/property/BaseAssociationEditorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/property/ChildAssociationEditorTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/property/ChildAssociationTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/property/PropertySheetGridTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/property/PropertySheetItemTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/property/PropertyTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/shelf/ClipboardShelfItemTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/shelf/RecentSpacesShelfItemTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/shelf/ShelfGroupTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/shelf/ShelfItemTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/shelf/ShelfTag.java delete mode 100644 war/src/main/java/org/alfresco/web/ui/repo/tag/shelf/ShortcutsShelfItemTag.java delete mode 100644 war/src/main/resources/alfresco/subsystems/Authentication/alfrescoNtlm/ntlm-filter-context.xml delete mode 100644 war/src/main/resources/alfresco/subsystems/Authentication/alfrescoNtlm/ntlm-filter.properties delete mode 100644 war/src/main/resources/alfresco/subsystems/Authentication/external/external-filter-context.xml delete mode 100644 war/src/main/resources/alfresco/subsystems/Authentication/kerberos/kerberos-filter-context.xml delete mode 100644 war/src/main/resources/alfresco/subsystems/Authentication/kerberos/kerberos-filter.properties delete mode 100644 war/src/main/resources/alfresco/subsystems/Authentication/passthru/ntlm-filter-context.xml delete mode 100644 war/src/main/resources/alfresco/subsystems/Authentication/passthru/ntlm-filter.properties diff --git a/pom.xml b/pom.xml index 226cd5936b..f15e83dc31 100644 --- a/pom.xml +++ b/pom.xml @@ -260,16 +260,6 @@ httpclient-cache 4.5.2 - - org.apache.myfaces.core - myfaces-api - 1.1.10 - - - org.apache.myfaces.core - myfaces-impl - 1.1.10 - org.springframework spring-aop diff --git a/war/pom.xml b/war/pom.xml index a8ce777806..86241a8156 100644 --- a/war/pom.xml +++ b/war/pom.xml @@ -76,12 +76,6 @@ 3.0.1 provided - - javax.servlet.jsp - jsp-api - 2.1 - provided - javax.portlet portlet-api diff --git a/war/src/main/java/org/alfresco/repo/web/scripts/portlet/WebClientPortletAuthenticatorFactory.java b/war/src/main/java/org/alfresco/repo/web/scripts/portlet/WebClientPortletAuthenticatorFactory.java deleted file mode 100644 index c138cf4bab..0000000000 --- a/war/src/main/java/org/alfresco/repo/web/scripts/portlet/WebClientPortletAuthenticatorFactory.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.repo.web.scripts.portlet; - -import java.io.IOException; - -import javax.portlet.PortletContext; -import javax.portlet.PortletException; -import javax.portlet.PortletSession; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; - -import org.alfresco.repo.web.scripts.servlet.AuthenticatorServlet; -import org.alfresco.web.app.servlet.AuthenticationStatus; -import org.springframework.extensions.webscripts.Authenticator; -import org.springframework.extensions.webscripts.WebScriptException; -import org.springframework.extensions.webscripts.Description.RequiredAuthentication; -import org.springframework.extensions.webscripts.portlet.PortletAuthenticatorFactory; - - -/** - * Portlet authenticator which synchronizes with the Alfresco Web Client authentication - * - * @author davidc - * @author dward - */ -public class WebClientPortletAuthenticatorFactory implements PortletAuthenticatorFactory -{ - /* (non-Javadoc) - * @see org.alfresco.web.scripts.portlet.PortletAuthenticatorFactory#create(javax.portlet.RenderRequest, javax.portlet.RenderResponse) - */ - public Authenticator create(RenderRequest req, RenderResponse res) - { - return new WebClientPortletAuthenticator(req, res); - } - - - public class WebClientPortletAuthenticator implements Authenticator - { - // dependencies - private RenderRequest req; - private RenderResponse res; - - /** - * Construct - * - * @param req RenderRequest - * @param res RenderResponse - */ - public WebClientPortletAuthenticator(RenderRequest req, RenderResponse res) - { - this.req = req; - this.res = res; - } - - /* (non-Javadoc) - * @see org.alfresco.web.scripts.Authenticator#authenticate(org.alfresco.web.scripts.Description.RequiredAuthentication, boolean) - */ - public boolean authenticate(RequiredAuthentication required, boolean isGuest) - { - PortletSession session = req.getPortletSession(); - req.setAttribute(AuthenticatorServlet.ATTR_REQUIRED_AUTH, required); - req.setAttribute(AuthenticatorServlet.ATTR_IS_GUEST, isGuest); - PortletContext context = session.getPortletContext(); - try - { - context.getNamedDispatcher(AuthenticatorServlet.SERVLET_NAME).include(req, res); - } - catch (PortletException e) - { - throw new WebScriptException("Failed to authenticate", e); - } - catch (IOException e) - { - throw new WebScriptException("Failed to authenticate", e); - } - AuthenticationStatus status = (AuthenticationStatus) req.getAttribute(AuthenticatorServlet.ATTR_AUTH_STATUS); - return !(status == null || status == AuthenticationStatus.Failure); - } - - /* (non-Javadoc) - * @see org.alfresco.web.scripts.Authenticator#emptyCredentials() - */ - public boolean emptyCredentials() - { - // Ticket - based authentication not supported - return true; - } - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/repo/web/scripts/portlet/WebScriptRepoPortlet.java b/war/src/main/java/org/alfresco/repo/web/scripts/portlet/WebScriptRepoPortlet.java deleted file mode 100644 index f39029d94c..0000000000 --- a/war/src/main/java/org/alfresco/repo/web/scripts/portlet/WebScriptRepoPortlet.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.repo.web.scripts.portlet; - -import java.io.IOException; - -import javax.portlet.ActionRequest; -import javax.portlet.ActionResponse; -import javax.portlet.PortletException; -import javax.portlet.PortletSecurityException; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; - -import org.alfresco.web.app.Application; -import org.springframework.extensions.webscripts.portlet.WebScriptPortlet; - - -/** - * Repository (server-tier) implementation of Web Script Portlet - * - * Informs Web Client Application of Portlet request. - * - * @author davidc - */ -public class WebScriptRepoPortlet extends WebScriptPortlet -{ - - /* (non-Javadoc) - * @see org.alfresco.web.scripts.portlet.WebScriptPortlet#processAction(javax.portlet.ActionRequest, javax.portlet.ActionResponse) - */ - @Override - public void processAction(ActionRequest req, ActionResponse res) throws PortletException, PortletSecurityException, IOException - { - Application.setInPortalServer(true); - try - { - super.processAction(req, res); - } - finally - { - Application.setInPortalServer(false); - } - } - - /* (non-Javadoc) - * @see org.alfresco.web.scripts.portlet.WebScriptPortlet#render(javax.portlet.RenderRequest, javax.portlet.RenderResponse) - */ - @Override - public void render(RenderRequest req, RenderResponse res) throws PortletException, PortletSecurityException, IOException - { - Application.setInPortalServer(true); - try - { - super.render(req, res); - } - finally - { - Application.setInPortalServer(false); - } - } - -} diff --git a/war/src/main/java/org/alfresco/repo/web/scripts/servlet/AuthenticatorServlet.java b/war/src/main/java/org/alfresco/repo/web/scripts/servlet/AuthenticatorServlet.java deleted file mode 100644 index edffc17db2..0000000000 --- a/war/src/main/java/org/alfresco/repo/web/scripts/servlet/AuthenticatorServlet.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.repo.web.scripts.servlet; - -import java.io.IOException; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.web.app.servlet.AuthenticationHelper; -import org.alfresco.web.app.servlet.AuthenticationStatus; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.extensions.webscripts.Description.RequiredAuthentication; - -/** - * This servlet serves as a useful 'subroutine' for portlets, which using their request dispatcher, can go 'through the - * looking glass' to this servlet and use the standard Alfresco servlet api-based authentication mechanisms. - * - * @author dward - * @deprecated 5.0 not exposed in web-client web.xml - */ -public class AuthenticatorServlet extends HttpServlet -{ - public static final String SERVLET_NAME = "authenticatorServlet"; - public static final String ATTR_IS_GUEST = "_alf_isGuest"; - public static final String ATTR_REQUIRED_AUTH = "_alf_requiredAuth"; - public static final String ATTR_AUTH_STATUS = "_alf_authStatus"; - - private static final long serialVersionUID = 5657140557243797744L; - - private static final Log logger = LogFactory.getLog(AuthenticatorServlet.class); - - /* - * (non-Javadoc) - * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, - * javax.servlet.http.HttpServletResponse) - */ - @Override - protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException - { - ServletContext context = getServletContext(); - boolean isGuest = (Boolean) req.getAttribute(ATTR_IS_GUEST); - RequiredAuthentication required = (RequiredAuthentication) req.getAttribute(ATTR_REQUIRED_AUTH); - AuthenticationStatus status; - if (isGuest && RequiredAuthentication.guest == required) - { - if (logger.isDebugEnabled()) - logger.debug("Authenticating as Guest"); - - status = AuthenticationHelper.authenticate(context, req, res, true); - } - else - { - if (logger.isDebugEnabled()) - logger.debug("Authenticating session"); - - status = AuthenticationHelper.authenticate(context, req, res, false, false); - } - req.setAttribute(ATTR_AUTH_STATUS, status); - } -} diff --git a/war/src/main/java/org/alfresco/repo/web/scripts/servlet/WebClientAuthenticatorFactory.java b/war/src/main/java/org/alfresco/repo/web/scripts/servlet/WebClientAuthenticatorFactory.java deleted file mode 100644 index 0e7142c1ba..0000000000 --- a/war/src/main/java/org/alfresco/repo/web/scripts/servlet/WebClientAuthenticatorFactory.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.repo.web.scripts.servlet; - -import java.io.IOException; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.web.app.servlet.AuthenticationHelper; -import org.alfresco.web.app.servlet.AuthenticationStatus; -import org.alfresco.web.app.servlet.BaseServlet; -import org.springframework.extensions.webscripts.Authenticator; -import org.springframework.extensions.webscripts.WebScriptException; -import org.springframework.extensions.webscripts.Description.RequiredAuthentication; -import org.springframework.extensions.webscripts.servlet.ServletAuthenticatorFactory; -import org.springframework.extensions.webscripts.servlet.WebScriptServletRequest; -import org.springframework.extensions.webscripts.servlet.WebScriptServletResponse; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.web.context.ServletContextAware; - - -/** - * Alfresco Web Client Authentication - * - * NOTE: 5.0 - Explorer client has been removed - as have the JSF bean definitions. This effectively mean this is now just - * a web Session based authenticator - ticket and user wrapper is stored in a Session and the JSESSIONID cookie is returned. - * No user prefs for language etc. are set due to the removal of Explorer beans. - * - * @author davidc - */ -public class WebClientAuthenticatorFactory implements ServletAuthenticatorFactory, ServletContextAware -{ - // Logger - private static final Log logger = LogFactory.getLog(WebClientAuthenticator.class); - - // dependencies - private ServletContext context; - - - /* (non-Javadoc) - * @see org.springframework.web.context.ServletContextAware#setServletContext(javax.servlet.ServletContext) - */ - public void setServletContext(ServletContext context) - { - this.context = context; - } - - /* (non-Javadoc) - * @see org.alfresco.web.scripts.servlet.ServletAuthenticatorFactory#create(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - public Authenticator create(WebScriptServletRequest req, WebScriptServletResponse res) - { - return new WebClientAuthenticator(req, res); - } - - - /** - * Alfresco Web Client Authentication - * - * @author davidc - */ - public class WebClientAuthenticator implements Authenticator - { - // dependencies - private WebScriptServletRequest servletReq; - private WebScriptServletResponse servletRes; - - private String ticket; - - /** - * Construct - * - * @param req WebScriptServletRequest - * @param res WebScriptServletResponse - */ - public WebClientAuthenticator(WebScriptServletRequest req, WebScriptServletResponse res) - { - this.servletReq = req; - this.servletRes = res; - - this.ticket = req.getParameter("ticket"); - } - - /* (non-Javadoc) - * @see org.alfresco.web.scripts.WebScriptServletAuthenticator#authenticate(org.alfresco.web.scripts.WebScriptDescription.RequiredAuthentication, boolean, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - public boolean authenticate(RequiredAuthentication required, boolean isGuest) - { - AuthenticationStatus status = null; - - try - { - // - // validate credentials - // - HttpServletRequest req = servletReq.getHttpServletRequest(); - HttpServletResponse res = servletRes.getHttpServletResponse(); - - - if (logger.isDebugEnabled()) - { - logger.debug("Alfresco ticket provided: " + (ticket != null && ticket.length() > 0)); - } - - if (! emptyCredentials()) - { - if (logger.isDebugEnabled()) - logger.debug("Authenticating ticket " + ticket); - - status = AuthenticationHelper.authenticate(context, req, res, ticket); - } - else - { - if (isGuest && RequiredAuthentication.guest == required) - { - if (logger.isDebugEnabled()) - logger.debug("Authenticating as Guest"); - - status = AuthenticationHelper.authenticate(context, req, res, true); - } - else - { - if (logger.isDebugEnabled()) - logger.debug("Authenticating session"); - - status = AuthenticationHelper.authenticate(context, req, res, false, false); - } - } - - // - // if not authorized, redirect to login page - // - if (status == null || status == AuthenticationStatus.Failure) - { - // ALF-13194: The client has asserted itself as guest, but guest authentication is forbidden. Signal - // with a 401 response rather than the login page! - if (isGuest && RequiredAuthentication.guest == required) - { - res.setStatus(401); - } - else - { - // authentication failed - now need to display the login page to the user, if asked to - if (logger.isDebugEnabled()) - logger.debug("Redirecting to Alfresco Login"); - - BaseServlet.redirectToLoginPage(req, res, context); - } - } - } - catch(IOException e) - { - throw new WebScriptException("Failed to authenticate", e); - } - - return !(status == null || status == AuthenticationStatus.Failure); - } - - /* (non-Javadoc) - * @see org.alfresco.web.scripts.Authenticator#emptyCredentials() - */ - public boolean emptyCredentials() - { - return (ticket == null || ticket.length() == 0); - } - - @Override - public String toString() - { - return servletReq.toString() + " [ticket=" + ticket + "]"; - } - } - -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/action/ActionEvaluator.java b/war/src/main/java/org/alfresco/web/action/ActionEvaluator.java deleted file mode 100644 index 3d9e21fca6..0000000000 --- a/war/src/main/java/org/alfresco/web/action/ActionEvaluator.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action; - -import java.io.Serializable; - -import org.alfresco.web.bean.repository.Node; - -/** - * Contract supported by all classes that provide dynamic evaluation for a UI action. - *

- * Evaluators are supplied with a Node instance context object. - *

- * The evaluator should decide if the action precondition is valid based on the appropriate - * logic and the properties etc. of the Node context and return the result. - * - * @author Kevin Roast - */ -public interface ActionEvaluator extends Serializable -{ - /** - * The evaluator should decide if the action precondition is valid based on the appropriate - * logic and the properties etc. of the Node context and return the result. - * - * @param node Node context for the action - * - * @return result of whether the action can proceed. - */ - public boolean evaluate(Node node); - - /** - * The evaluator should decide if the action precondition is valid based on the appropriate - * logic and the state etc. of the given object and return the result. - * - * @param obj The object the action is for - * - * @return result of whether the action can proceed. - */ - public boolean evaluate(Object obj); -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/AddTranslationEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/AddTranslationEvaluator.java deleted file mode 100644 index 60c87fb891..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/AddTranslationEvaluator.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.ml.MultilingualContentService; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.users.UserPreferencesBean; -import org.alfresco.web.bean.ml.MultilingualUtils; -import org.alfresco.web.bean.repository.Node; - -/** - * Evaluates whether the Add Translation (with or without content) action should be visible. - * - * If the node is not already Multilingual, locked, or if a translation exists for each available - * filter language, don't allow the action. - * - * The current user can add a translation to a translation set only if he has enough right to add - * a content to the space where the pivot translation is located in. - * - * @author Yannick Pignot - */ -public class AddTranslationEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = -1513219397606505237L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - boolean isNodeMultililingal = node.hasAspect(ContentModel.ASPECT_MULTILINGUAL_DOCUMENT); - boolean isMLContainer = node.getType().equals(ContentModel.TYPE_MULTILINGUAL_CONTAINER); - - // the node must be multiligual (translation or ml container) - if(isNodeMultililingal || isMLContainer) - { - FacesContext fc = FacesContext.getCurrentInstance(); - - // the current user must have enough right to add a content to the space - // where the pivot translation is located in - if(MultilingualUtils.canAddChildrenToPivotSpace(node, fc)) - { - MultilingualContentService mlservice = - (MultilingualContentService) FacesHelper.getManagedBean(fc, "MultilingualContentService"); - - UserPreferencesBean userprefs = - (UserPreferencesBean) FacesHelper.getManagedBean(fc, "UserPreferencesBean"); - - // the number of translation of this document - int availableTranslationCount = mlservice.getTranslations(node.getNodeRef()).size(); - // the total number of available languages for the translation - int contentFilterLanguagesCount = userprefs.getContentFilterLanguages(false).length; - - // the number of translation must be < to the total number of available language for the content filter - return (availableTranslationCount < contentFilterLanguagesCount); - } - else - { - return false; - } - } - else - { - return false; - } - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/ApproveDocEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/ApproveDocEvaluator.java deleted file mode 100644 index 1dea9830be..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/ApproveDocEvaluator.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import java.util.Map; - -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.web.bean.repository.Node; - -/** - * UI Action Evaluator - 'Approve' workflow step for document or space. - * - * @author Kevin Roast - */ -public class ApproveDocEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = 2958297435415449179L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - Map properties = node.getProperties(); - - Boolean approveMove = (Boolean) properties.get("app:approveMove"); - boolean isMove = approveMove == null ? false : approveMove; - - boolean canProceed = (properties.get("app:approveStep") != null) && !node.isLocked(); - //If this approval is going to result in a move of the node then we check whether the user - //has permission. The delete permission is required in order to move a node (odd, perhaps, but true). - canProceed &= (!isMove || node.hasPermission(PermissionService.DELETE)); - - return canProceed; - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/ApproveNonDraftDocEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/ApproveNonDraftDocEvaluator.java deleted file mode 100644 index 7a9438b729..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/ApproveNonDraftDocEvaluator.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import org.alfresco.model.ContentModel; -import org.alfresco.web.bean.repository.Node; - -/** - * UI Action Evaluator - 'Approve' workflow step for document. - * - * @author Kevin Roast - */ -public class ApproveNonDraftDocEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = -277600395385704689L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - return (node.getProperties().get("app:approveStep") != null && - node.isLocked() == false && - node.hasAspect(ContentModel.ASPECT_WORKING_COPY) == false); - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/BaseActionEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/BaseActionEvaluator.java deleted file mode 100644 index 2c2dc7243d..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/BaseActionEvaluator.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import javax.faces.context.FacesContext; - -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.service.transaction.TransactionService; -import org.alfresco.web.action.ActionEvaluator; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; - -/** - * Base class for all action evaluators. - * - * @author gavinc - */ -public class BaseActionEvaluator implements ActionEvaluator -{ - public boolean evaluate(Node node) - { - // Allow the action by default - - return true; - } - - public boolean evaluate(final Object obj) - { - // if a Node object is passed to this method call - // the explicit evaluate(Node) method otherwise - // allow the action by default. - - if (obj instanceof Node) - { - RetryingTransactionCallback txnCallback = new RetryingTransactionCallback() - { - @Override - public Boolean execute() throws Throwable - { - return evaluate((Node)obj); - } - }; - TransactionService txnService = - Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getTransactionService(); - return txnService.getRetryingTransactionHelper().doInTransaction(txnCallback, true, true); - } - else - { - return true; - } - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/CancelCheckoutDocEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/CancelCheckoutDocEvaluator.java deleted file mode 100644 index e81ca3a9cb..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/CancelCheckoutDocEvaluator.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.web.bean.repository.Node; - -/** - * UI Action Evaluator - Cancel checkout document. - * - * @author Kevin Roast - */ -public class CancelCheckoutDocEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = -9015403093449070254L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - return (node.hasAspect(ContentModel.ASPECT_WORKING_COPY) && - node.getProperties().get(ContentModel.PROP_WORKING_COPY_MODE) == null && - node.hasPermission(PermissionService.CANCEL_CHECK_OUT)); - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/CancelEditingDocEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/CancelEditingDocEvaluator.java deleted file mode 100644 index 280c9720a8..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/CancelEditingDocEvaluator.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.web.bean.repository.Node; - -/** - * UI Action Evaluator - Cancel editing document. - */ -public class CancelEditingDocEvaluator extends BaseActionEvaluator -{ - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - return (node.hasAspect(ContentModel.ASPECT_WORKING_COPY) && - node.getProperties().get(ContentModel.PROP_WORKING_COPY_MODE) != null && - node.hasPermission(PermissionService.CANCEL_CHECK_OUT)); - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/CancelWorkflowEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/CancelWorkflowEvaluator.java deleted file mode 100644 index 20906c4dd7..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/CancelWorkflowEvaluator.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.workflow.WorkflowTask; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.repository.User; - -/** - * UI Action Evaluator for cancel workflow action. The action - * is only allowed if the workflow the task belongs to was - * started by the current user. - * - * @author gavinc - */ -public class CancelWorkflowEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = 7663087149225546333L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - boolean result = false; - FacesContext context = FacesContext.getCurrentInstance(); - - // get the task from the node - WorkflowTask task = (WorkflowTask)node.getProperties().get("workflowTask"); - if (task != null) - { - NodeRef initiator = task.path.instance.initiator; - if (initiator != null) - { - // find the current username - User user = Application.getCurrentUser(context); - String currentUserName = user.getUserName(); - - // get the username of the initiator - NodeService nodeSvc = Repository.getServiceRegistry( - context).getNodeService(); - String userName = (String)nodeSvc.getProperty(initiator, ContentModel.PROP_USERNAME); - - // if the current user started the workflow allow the cancel action - if (currentUserName.equals(userName)) - { - result = true; - } - } - } - - return result; - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/CheckinDocEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/CheckinDocEvaluator.java deleted file mode 100644 index b82620108e..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/CheckinDocEvaluator.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.web.bean.repository.Node; - -/** - * UI Action Evaluator - Checkin document. - * - * @author Kevin Roast - */ -public class CheckinDocEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = 5398249535631219663L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - return (node.hasAspect(ContentModel.ASPECT_WORKING_COPY) && - node.getProperties().get(ContentModel.PROP_WORKING_COPY_MODE) == null && - node.hasPermission(PermissionService.CHECK_IN)); - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/CheckoutDocEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/CheckoutDocEvaluator.java deleted file mode 100644 index 1c991a2550..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/CheckoutDocEvaluator.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; - -/** - * UI Action Evaluator - Checkout document. - * - * @author Kevin Roast - */ -public class CheckoutDocEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = 5510366635124591353L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - DictionaryService dd = Repository.getServiceRegistry( - FacesContext.getCurrentInstance()).getDictionaryService(); - - return dd.isSubClass(node.getType(), ContentModel.TYPE_CONTENT) && - ((node.hasPermission(PermissionService.CHECK_OUT) && - (node.isLocked() == false && - node.hasAspect(ContentModel.ASPECT_WORKING_COPY) == false) && - node.hasAspect(ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION) == false)); - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/CreateForumMLNodeEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/CreateForumMLNodeEvaluator.java deleted file mode 100644 index bd32aecbf8..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/CreateForumMLNodeEvaluator.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ForumModel; -import org.alfresco.web.bean.ml.MultilingualUtils; -import org.alfresco.web.bean.repository.Node; - -/** - * UI Action Evaluator - Create a forum around a multilingual content node. - * - * @author Yanick Pignot - */ -public class CreateForumMLNodeEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = -8621940623410511065L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - // the current user must have enough right to add a content to the space - // where the pivot translation is located in - return MultilingualUtils.canAddChildrenToPivotSpace(node, FacesContext.getCurrentInstance()) - && node.hasAspect(ForumModel.ASPECT_DISCUSSABLE) == false - && node.isLocked() == false; - - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/CreateForumNodeEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/CreateForumNodeEvaluator.java deleted file mode 100644 index 4d5cb17e0e..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/CreateForumNodeEvaluator.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import org.alfresco.model.ForumModel; -import org.alfresco.web.bean.repository.Node; - -/** - * UI Action Evaluator - Create a forum around a node. - * - * @author Kevin Roast - */ -public class CreateForumNodeEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = -5132048668011887505L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - return (node.hasAspect(ForumModel.ASPECT_DISCUSSABLE) == false && - node.isLocked() == false); - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/CutNodeEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/CutNodeEvaluator.java deleted file mode 100644 index 1d8cb3b339..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/CutNodeEvaluator.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.web.bean.ml.MultilingualUtils; -import org.alfresco.web.bean.repository.Node; - -/** - * Evaluates whether the Cut Node action should be visible. - * - * Among all available operations over non-multilingual documents (i.e. copy, - * delete, start discussion, etc), there is a missing one: Move. - * Translations cannot be moved due to the exiting link it has with the logical - * document. Despite it is technically achievable, it could be functionally - * troublesome. Spreading translations of the same semantic message among several - * spaces could lead to confusion and problems. - * - * If the node to move is a mlContainer, the user must have enough right to delete each translation - * - * @author Yannick Pignot - */ -public class CutNodeEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = 5162681242056158214L; - - public boolean evaluate(Node node) - { - - FacesContext fc = FacesContext.getCurrentInstance(); - - // the node to delete is a ml container, test if the user has enought right on each translation - if(node.getType().equals(ContentModel.TYPE_MULTILINGUAL_CONTAINER)) - { - return MultilingualUtils.canMoveEachTranslation(node, fc); - } - - - boolean eval = true; - - // impossible to cut/copy a translation without content. - if (node.getAspects().contains(ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION)) - { - eval = false; - } - else - { - eval = !node.getAspects().contains(ContentModel.ASPECT_MULTILINGUAL_DOCUMENT); - } - - return eval; - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/DeleteDocEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/DeleteDocEvaluator.java deleted file mode 100644 index dbad9dd8f0..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/DeleteDocEvaluator.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.ml.MultilingualContentService; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.ml.MultilingualUtils; -import org.alfresco.web.bean.repository.Node; - -/** - * UI Action Evaluator - Delete document. - * - * @author Kevin Roast - */ -public class DeleteDocEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = 5742287199692844685L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - FacesContext fc = FacesContext.getCurrentInstance(); - - // the node to delete is a ml container, test if the user has enought right on each translation - if(node.getType().equals(ContentModel.TYPE_MULTILINGUAL_CONTAINER)) - { - return MultilingualUtils.canDeleteEachTranslation(node, fc); - } - - boolean isPivot = false; - - // special case for multilingual documents - if (node.getAspects().contains(ContentModel.ASPECT_MULTILINGUAL_DOCUMENT)) - { - MultilingualContentService mlservice = - (MultilingualContentService) FacesHelper.getManagedBean(fc, "MultilingualContentService"); - - // if the translation is the last translation, user can delete it - if (mlservice.getTranslations(node.getNodeRef()).size() == 1) - { - isPivot = false; - } - // Else if the node is the pivot language, user can't delete it - else if (mlservice.getPivotTranslation(node.getNodeRef()).getId() - .equalsIgnoreCase(node.getNodeRef().getId())) - { - isPivot = true; - } - // finally, the node is not the pivot translation, user can delete it - } - - return (node.isLocked() == false && - node.hasAspect(ContentModel.ASPECT_WORKING_COPY) == false && - isPivot == false); - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/DiscussNodeEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/DiscussNodeEvaluator.java deleted file mode 100644 index a15b30c6c1..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/DiscussNodeEvaluator.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import java.util.List; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ForumModel; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.namespace.RegexQNamePattern; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; - -/** - * UI Action Evaluator - Discuss a node. - * - * @author Kevin Roast - */ -public class DiscussNodeEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = 8754174908349998903L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - boolean result = false; - - if (node.hasAspect(ForumModel.ASPECT_DISCUSSABLE)) - { - NodeService nodeService = Repository.getServiceRegistry( - FacesContext.getCurrentInstance()).getNodeService(); - List children = nodeService.getChildAssocs( - node.getNodeRef(), ForumModel.ASSOC_DISCUSSION, - RegexQNamePattern.MATCH_ALL); - - // make sure there is one visible child association for the node - if (children.size() == 1) - { - result = true; - } - } - - return result; - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/DiscussionCopyEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/DiscussionCopyEvaluator.java deleted file mode 100644 index 16154138a2..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/DiscussionCopyEvaluator.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.model.ForumModel; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; - -/** - * Evaluates whether the copy action should be visible. - * - * If the node is a discussion don't allow the action. - * - * @author gavinc - */ -public class DiscussionCopyEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = -4080878553011296677L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - boolean result = true; - - // if the node in question is a forum... - if (node.getType().equals(ForumModel.TYPE_FORUM)) - { - // get the association type - FacesContext context = FacesContext.getCurrentInstance(); - NodeService nodeService = Repository.getServiceRegistry(context).getNodeService(); - - ChildAssociationRef parentAssoc = nodeService.getPrimaryParent(node.getNodeRef()); - QName assocType = parentAssoc.getTypeQName(); - - // only allow the action if the association type is not the discussion assoc - result = (assocType.equals(ForumModel.ASSOC_DISCUSSION) == false); - } - - // impossible to copy a translation without content. - if (result && node.getAspects().contains(ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION)) - { - result = false; - } - - if (!node.hasPermission(PermissionService.READ)) - { - result = false; - } - - return result; - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/DiscussionCutEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/DiscussionCutEvaluator.java deleted file mode 100644 index a5d30b773a..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/DiscussionCutEvaluator.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ForumModel; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; - -/** - * Evaluates whether the cut action should be visible. - * - * If the node is a discussion don't allow the action. - * - * @author gavinc - */ -public class DiscussionCutEvaluator extends CutNodeEvaluator -{ - private static final long serialVersionUID = 7260556874788184200L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - boolean result = super.evaluate(node); - - // if the node in question is a forum... - if (result && node.getType().equals(ForumModel.TYPE_FORUM)) - { - // get the association type - FacesContext context = FacesContext.getCurrentInstance(); - NodeService nodeService = Repository.getServiceRegistry(context).getNodeService(); - - ChildAssociationRef parentAssoc = nodeService.getPrimaryParent(node.getNodeRef()); - QName assocType = parentAssoc.getTypeQName(); - - // only allow the action if the association type is not the discussion assoc - result = (assocType.equals(ForumModel.ASSOC_DISCUSSION) == false); - } - - return result; - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/DoneEditingDocEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/DoneEditingDocEvaluator.java deleted file mode 100644 index a3ab8c9713..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/DoneEditingDocEvaluator.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.web.bean.repository.Node; - -/** - * UI Action Evaluator - Done editing document. - */ -public class DoneEditingDocEvaluator extends BaseActionEvaluator -{ - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - return (node.getProperties().get(ContentModel.PROP_WORKING_COPY_MODE) != null && - node.hasAspect(ContentModel.ASPECT_WORKING_COPY) && - node.hasPermission(PermissionService.CHECK_IN)); - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/EditDocCIFSEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/EditDocCIFSEvaluator.java deleted file mode 100644 index 4ec36c737c..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/EditDocCIFSEvaluator.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.coci.EditOnlineDialog; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; - -/** - * UI Action Evaluator - Edit document via CIFS. - * - * @author Kevin Roast - */ -public class EditDocCIFSEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = -8988276140748731926L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - FacesContext fc = FacesContext.getCurrentInstance(); - DictionaryService dd = Repository.getServiceRegistry(fc).getDictionaryService(); - - boolean result = false; - - // if the node is inline editable, the default http behaviour should always be used - if (dd.isSubClass(node.getType(), ContentModel.TYPE_CONTENT)) - { - if (node.hasAspect(ApplicationModel.ASPECT_INLINEEDITABLE) == false && - "cifs".equals(Application.getClientConfig(fc).getEditLinkType())) - { - if ((node.isWorkingCopyOwner() == true && node.getProperties().get(ContentModel.PROP_WORKING_COPY_MODE) != null && - node.getProperties().get(ContentModel.PROP_WORKING_COPY_MODE).equals(EditOnlineDialog.ONLINE_EDITING))|| - (node.hasAspect(ContentModel.ASPECT_WORKING_COPY) && node.hasPermission(PermissionService.WRITE)) || - (node.isLocked() == false && node.hasAspect(ContentModel.ASPECT_WORKING_COPY) == false)) - { - result = true; - } - } - } - - return result; - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/EditDocHttpEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/EditDocHttpEvaluator.java deleted file mode 100644 index cb3d9f1135..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/EditDocHttpEvaluator.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.coci.EditOnlineDialog; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; - -/** - * UI Action Evaluator - Edit document via HTTP or inline edit. - * - * @author Kevin Roast - */ -public class EditDocHttpEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = -3694679925715830430L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - FacesContext fc = FacesContext.getCurrentInstance(); - DictionaryService dd = Repository.getServiceRegistry(fc).getDictionaryService(); - - boolean result = false; - - // Since the reader returned of an empty translation is the reader of it's pivot translation, it makes - // no sens to edit it on-line. - if(node.getAspects().contains(ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION)) - { - //result = false - } - // if the node is inline editable, the default http behaviour should - // always be used otherwise the configured approach is used - else if (dd.isSubClass(node.getType(), ContentModel.TYPE_CONTENT)) - { - if (node.hasAspect(ApplicationModel.ASPECT_INLINEEDITABLE) == true && - node.getProperties().get(ApplicationModel.PROP_EDITINLINE) != null && - ((Boolean)node.getProperties().get(ApplicationModel.PROP_EDITINLINE)).booleanValue() == true) - { - if ((node.isWorkingCopyOwner() == true && node.getProperties().get(ContentModel.PROP_WORKING_COPY_MODE) != null && - node.getProperties().get(ContentModel.PROP_WORKING_COPY_MODE).equals(EditOnlineDialog.ONLINE_EDITING)) || - (node.hasAspect(ContentModel.ASPECT_WORKING_COPY) && node.hasPermission(PermissionService.WRITE)) || - (node.isLocked() == false && node.hasAspect(ContentModel.ASPECT_WORKING_COPY) == false)) - { - result = true; - } - } - } - - return result; - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/EditDocOfflineEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/EditDocOfflineEvaluator.java deleted file mode 100644 index 999fa3caf9..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/EditDocOfflineEvaluator.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - - -/** - * UI Action Evaluator - Offline Document Editing. - */ -public class EditDocOfflineEvaluator extends CheckoutDocEvaluator -{ -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/EditDocOnlineCIFSEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/EditDocOnlineCIFSEvaluator.java deleted file mode 100644 index dd9d0d8363..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/EditDocOnlineCIFSEvaluator.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.coci.EditOnlineDialog; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; - -/** - * UI Action Evaluator - Edit document online via CIFS. - */ -public class EditDocOnlineCIFSEvaluator extends CheckoutDocEvaluator -{ - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - FacesContext fc = FacesContext.getCurrentInstance(); - DictionaryService dd = Repository.getServiceRegistry(fc).getDictionaryService(); - - boolean result = false; - - // if the node is inline editable, the inline online editing should always be used - if (dd.isSubClass(node.getType(), ContentModel.TYPE_CONTENT)) - { - Map props = node.getProperties(); - if ("cifs".equals(Application.getClientConfig(fc).getEditLinkType()) && - (!node.hasAspect(ApplicationModel.ASPECT_INLINEEDITABLE) || - props.get(ApplicationModel.PROP_EDITINLINE) == null || - !((Boolean)props.get(ApplicationModel.PROP_EDITINLINE)).booleanValue())) - { - if (node.hasAspect(ContentModel.ASPECT_WORKING_COPY)) - { - result = (EditOnlineDialog.ONLINE_EDITING.equals(props.get(ContentModel.PROP_WORKING_COPY_MODE))); - } - else - { - result = super.evaluate(node); - } - } - } - - return result; - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/EditDocOnlineHttpEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/EditDocOnlineHttpEvaluator.java deleted file mode 100644 index 3612283c39..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/EditDocOnlineHttpEvaluator.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.web.bean.coci.EditOnlineDialog; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; - -/** - * UI Action Evaluator - Edit document online via http. - */ -public class EditDocOnlineHttpEvaluator extends CheckoutDocEvaluator -{ - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - FacesContext fc = FacesContext.getCurrentInstance(); - DictionaryService dd = Repository.getServiceRegistry(fc).getDictionaryService(); - - boolean result = false; - - if (node.hasAspect(ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION)) - { - // this branch from EditDocHttpEvaluator - // skip, result = false - } - else if (dd.isSubClass(node.getType(), ContentModel.TYPE_CONTENT)) - { - Map props = node.getProperties(); - if ((node.hasAspect(ApplicationModel.ASPECT_INLINEEDITABLE) && - props.get(ApplicationModel.PROP_EDITINLINE) != null && - ((Boolean)props.get(ApplicationModel.PROP_EDITINLINE)).booleanValue())) - { - if (node.hasAspect(ContentModel.ASPECT_WORKING_COPY)) - { - result = EditOnlineDialog.ONLINE_EDITING.equals(props.get(ContentModel.PROP_WORKING_COPY_MODE)); - } - else - { - result = super.evaluate(node); - } - } - } - - return result; - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/EditDocOnlineWebDavEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/EditDocOnlineWebDavEvaluator.java deleted file mode 100644 index 9480ed0b73..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/EditDocOnlineWebDavEvaluator.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.coci.EditOfflineDialog; -import org.alfresco.web.bean.coci.EditOnlineDialog; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; - -/** - * UI Action Evaluator - Edit document online via WebDav. - */ -public class EditDocOnlineWebDavEvaluator extends CheckoutDocEvaluator -{ - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - FacesContext fc = FacesContext.getCurrentInstance(); - DictionaryService dd = Repository.getServiceRegistry(fc).getDictionaryService(); - - boolean result = false; - - // if the node is inline editable, the inline online editing should always be used - if (dd.isSubClass(node.getType(), ContentModel.TYPE_CONTENT)) - { - Map props = node.getProperties(); - - if ("webdav".equals(Application.getClientConfig(fc).getEditLinkType()) && - (!node.hasAspect(ApplicationModel.ASPECT_INLINEEDITABLE) || - props.get(ApplicationModel.PROP_EDITINLINE) == null || - !((Boolean)props.get(ApplicationModel.PROP_EDITINLINE)).booleanValue())) - { - if (node.hasAspect(ContentModel.ASPECT_WORKING_COPY)) - { - result = (EditOnlineDialog.ONLINE_EDITING.equals(props.get(ContentModel.PROP_WORKING_COPY_MODE))); - } - else - { - result = super.evaluate(node); - } - } - } - - return result; - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/EditDocWebDavEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/EditDocWebDavEvaluator.java deleted file mode 100644 index 9eb12b9933..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/EditDocWebDavEvaluator.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.coci.EditOnlineDialog; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; - -/** - * UI Action Evaluator - Edit document via Webdav. - * - * @author Kevin Roast - */ -public class EditDocWebDavEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = 293342561997588700L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - FacesContext fc = FacesContext.getCurrentInstance(); - DictionaryService dd = Repository.getServiceRegistry(fc).getDictionaryService(); - - boolean result = false; - - // if the node is inline editable, the default http behaviour should always be used - if (dd.isSubClass(node.getType(), ContentModel.TYPE_CONTENT)) - { - if (node.hasAspect(ApplicationModel.ASPECT_INLINEEDITABLE) == false && - "webdav".equals(Application.getClientConfig(fc).getEditLinkType())) - { - if ((node.isWorkingCopyOwner() == true && node.getProperties().get(ContentModel.PROP_WORKING_COPY_MODE).equals(EditOnlineDialog.ONLINE_EDITING)) || - (node.hasAspect(ContentModel.ASPECT_WORKING_COPY) && node.hasPermission(PermissionService.WRITE)) || - (node.isLocked() == false && node.hasAspect(ContentModel.ASPECT_WORKING_COPY) == false)) - { - result = true; - } - } - } - - return result; - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/EditPostEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/EditPostEvaluator.java deleted file mode 100644 index 41cc0fe9bb..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/EditPostEvaluator.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.repo.site.SiteModel; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.web.bean.repository.Node; - -/** - * UI Action Evaluator - Allow comment editing only to coordinators, site managers, creator and owner - */ -public class EditPostEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = -5544290216536965941L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - String currentUser = AuthenticationUtil.getFullyAuthenticatedUser(); - return (currentUser.equalsIgnoreCase((String)node.getProperties().get(ContentModel.PROP_OWNER)) || - currentUser.equalsIgnoreCase((String)node.getProperties().get(ContentModel.PROP_CREATOR)) || - node.hasPermission(SiteModel.SITE_MANAGER) || - node.hasPermission(PermissionService.COORDINATOR)); - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/ForumsCheckinDocEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/ForumsCheckinDocEvaluator.java deleted file mode 100644 index 554c3ad6ea..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/ForumsCheckinDocEvaluator.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.model.ForumModel; -import org.alfresco.service.cmr.coci.CheckOutCheckInService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; - -/** - * UI Action Evaluator - Checkin a document with potentially a Forum attached. - * - * @author Kevin Roast - */ -public class ForumsCheckinDocEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = -924897450989526336L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - boolean allow = false; - - if (node.hasAspect(ContentModel.ASPECT_WORKING_COPY) && - node.getProperties().get(ContentModel.PROP_WORKING_COPY_MODE) == null) - { - if (node.hasAspect(ForumModel.ASPECT_DISCUSSABLE)) - { - CheckOutCheckInService checkOutCheckInService = - Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getCheckOutCheckInService(); - // get the original locked node (via the copiedfrom aspect) - NodeRef lockedNodeRef = checkOutCheckInService.getCheckedOut(node.getNodeRef()); - if (lockedNodeRef != null) - { - Node lockedNode = new Node(lockedNodeRef); - allow = (node.hasPermission(PermissionService.CHECK_IN) && - lockedNode.hasPermission(PermissionService.CONTRIBUTOR)); - } - } - else - { - // there is no discussion so just check they have checkin permission for the node - allow = node.hasPermission(PermissionService.CHECK_IN); - } - } - - return allow; - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/GroupActionEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/GroupActionEvaluator.java deleted file mode 100644 index 2720aa6a36..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/GroupActionEvaluator.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import java.util.Map; - -import org.alfresco.web.bean.groups.GroupsDialog; - - -/** - * Evaluator that determines whether the add group user action should - * be visible - only visible when the dialog is not showing the root - * group. - * - * @author Gavin Cornwell - */ -public class GroupActionEvaluator extends BaseActionEvaluator -{ - @Override - public boolean evaluate(Object obj) - { - boolean result = true; - - if (obj instanceof GroupsDialog) - { - // if the object is the GroupsDialog check whether the group is null, - // if it is it represents the root group so disallow the action - result = (((GroupsDialog)obj).getGroup() != null); - } - else if (obj instanceof Map) - { - // if the object is a Map retrieve the group and check for null, - // if it is it represents the root group so disallow the action - Object group = ((Map)obj).get(GroupsDialog.PARAM_GROUP); - result = (group != null); - } - else - { - result = super.evaluate(obj); - } - - return result; - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/MakeMultilingualEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/MakeMultilingualEvaluator.java deleted file mode 100644 index 7709a75310..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/MakeMultilingualEvaluator.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.users.UserPreferencesBean; -import org.alfresco.web.bean.repository.Node; - -/** - * Evaluates whether the Make Multilingual action should be visible. - * - * If the node is already Multilingual don't allow the action. - * - * @author Yannick Pignot - */ -public class MakeMultilingualEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = 4417014487557744219L; - - public boolean evaluate(Node node) - { - FacesContext fc = FacesContext.getCurrentInstance(); - - UserPreferencesBean userprefs = - (UserPreferencesBean) FacesHelper.getManagedBean(fc, "UserPreferencesBean"); - - // the total number of available languages for the translation have to be greather that 0 - int contentFilterLanguagesCount = userprefs.getContentFilterLanguages(false).length; - - return (node.isLocked() == false && - node.hasAspect(ContentModel.ASPECT_WORKING_COPY) == false && - node.hasAspect(ContentModel.ASPECT_MULTILINGUAL_DOCUMENT) == false && - contentFilterLanguagesCount > 0); - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/MultilingualDetailsEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/MultilingualDetailsEvaluator.java deleted file mode 100644 index 706c204e7e..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/MultilingualDetailsEvaluator.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import org.alfresco.model.ContentModel; -import org.alfresco.web.bean.repository.Node; - -/** - * Evaluates whether the Manage Multinlingual Details action should be visible. - * - * The action is available only if the node is a translation. - * - * @author Yannick Pignot - */ -public class MultilingualDetailsEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = 1154993208046462796L; - - public boolean evaluate(Node node) - { - return (node.hasAspect(ContentModel.ASPECT_MULTILINGUAL_DOCUMENT) == true); - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/NewEditionEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/NewEditionEvaluator.java deleted file mode 100644 index 8893896e1c..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/NewEditionEvaluator.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.bean.ml.MultilingualUtils; -import org.alfresco.web.bean.repository.Node; - -/** - * Evaluates whether the new edition wizard action should be visible. - * - * The creation of a new edtion implies the deletion of each translation and the creation - * of new content in the space - * - * @author Yanick Pignot - */ -public class NewEditionEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = -7511956951071280506L; - - public boolean evaluate(Node node) - { - FacesContext fc = FacesContext.getCurrentInstance(); - return MultilingualUtils.canStartNewEditon(node, fc); - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/RejectDocEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/RejectDocEvaluator.java deleted file mode 100644 index 6302e7e86c..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/RejectDocEvaluator.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import org.alfresco.web.bean.repository.Node; - -/** - * UI Action Evaluator - 'Reject' workflow step for document or space. - * - * @author Kevin Roast - */ -public class RejectDocEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = -7733947744617999298L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - return (node.getProperties().get("app:rejectStep") != null && - node.isLocked() == false); - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/RejectNonDraftDocEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/RejectNonDraftDocEvaluator.java deleted file mode 100644 index 240cc4eec3..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/RejectNonDraftDocEvaluator.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import org.alfresco.model.ContentModel; -import org.alfresco.web.bean.repository.Node; - -/** - * UI Action Evaluator - 'Reject' workflow step for document. - * - * @author Kevin Roast - */ -public class RejectNonDraftDocEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = 6296671033469500696L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - return (node.getProperties().get("app:rejectStep") != null && - node.isLocked() == false && - node.hasAspect(ContentModel.ASPECT_WORKING_COPY) == false); - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/ShortcutNodeEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/ShortcutNodeEvaluator.java deleted file mode 100644 index f920157466..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/ShortcutNodeEvaluator.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.NavigationBean; -import org.alfresco.web.bean.repository.Node; - -/** - * UI Action Evaluator - Create a shortcut to a node. - * - * @author Kevin Roast - */ -public class ShortcutNodeEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = 8768692540125721144L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - NavigationBean nav = - (NavigationBean)FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), NavigationBean.BEAN_NAME); - return (nav.getIsGuest() == false); - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/StartWorkflowEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/StartWorkflowEvaluator.java deleted file mode 100644 index fcdd3b10ea..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/StartWorkflowEvaluator.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.workflow.BPMEngineRegistry; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.NavigationBean; -import org.alfresco.web.bean.repository.Node; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.jsf.FacesContextUtils; - -/** - * UI Action Evaluator - Start workflow on a node. - * - * @author gavinc - */ -public class StartWorkflowEvaluator extends BaseActionEvaluator -{ - private static final String BPM_ENGINE_BEAN_NAME = "bpm_engineRegistry"; - private static final long serialVersionUID = 3110333488835027710L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - FacesContext facesContext = FacesContext.getCurrentInstance(); - NavigationBean nav = - (NavigationBean)FacesHelper.getManagedBean(facesContext, NavigationBean.BEAN_NAME); - - // determine whether the workflow services are active - boolean workflowPresent = false; - WebApplicationContext springContext = FacesContextUtils.getRequiredWebApplicationContext(facesContext); - BPMEngineRegistry bpmReg = (BPMEngineRegistry)springContext.getBean(BPM_ENGINE_BEAN_NAME); - if (bpmReg != null) - { - String[] components = bpmReg.getWorkflowComponents(); - workflowPresent = (components != null && components.length > 0); - } - - return (workflowPresent && nav.getIsGuest() == false && - node.hasAspect(ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION) == false); - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/TakeOwnershipDocEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/TakeOwnershipDocEvaluator.java deleted file mode 100644 index 2ec162340a..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/TakeOwnershipDocEvaluator.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import org.alfresco.web.bean.repository.Node; - -/** - * UI Action Evaluator - Take ownership of a document. - * - * @author Kevin Roast - */ -public class TakeOwnershipDocEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = 3966463533922521230L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - return (node.isLocked() == false); - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/UnlockDocEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/UnlockDocEvaluator.java deleted file mode 100644 index 45f957242a..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/UnlockDocEvaluator.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import javax.faces.context.FacesContext; - -import org.alfresco.service.cmr.coci.CheckOutCheckInService; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.repository.Node; - -/** - * UI Action Evaluator - Unlock a locked document. - * - * @author Kevin Roast - */ -public class UnlockDocEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = -7056759932698306087L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - if (node.isLocked()) - { - FacesContext fc = FacesContext.getCurrentInstance(); - CheckOutCheckInService checkOutCheckInService = (CheckOutCheckInService) FacesHelper.getManagedBean(fc, "CheckoutCheckinService"); - if (checkOutCheckInService.getWorkingCopy(node.getNodeRef()) == null) - { - return true; - } - } - - return false; - } -} diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/UnlockedDocEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/UnlockedDocEvaluator.java deleted file mode 100644 index 31f0629ae9..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/UnlockedDocEvaluator.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import org.alfresco.web.bean.repository.Node; - -/** - * UI Action Evaluator - Proceed if the document is not locked. - * - * @author Kevin Roast - */ -public class UnlockedDocEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = -3216759932698306123L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - return (node.isLocked() == false); - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/UpdateDocEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/UpdateDocEvaluator.java deleted file mode 100644 index a4818fd1ef..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/UpdateDocEvaluator.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.web.bean.coci.EditOfflineDialog; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; - -/** - * UI Action Evaluator - Update document content. - * - * @author Kevin Roast - */ -public class UpdateDocEvaluator extends BaseActionEvaluator -{ - private static final long serialVersionUID = 6030963610213633893L; - - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - DictionaryService dd = Repository.getServiceRegistry( - FacesContext.getCurrentInstance()).getDictionaryService(); - - boolean isOfflineEditing = - (EditOfflineDialog.OFFLINE_EDITING.equals(node.getProperties().get(ContentModel.PROP_WORKING_COPY_MODE))); - - return dd.isSubClass(node.getType(), ContentModel.TYPE_CONTENT) && - ((node.isWorkingCopyOwner() && !isOfflineEditing) || - (!node.isLocked() && !node.hasAspect(ContentModel.ASPECT_WORKING_COPY))); - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/action/evaluator/UploadNewVersionEvaluator.java b/war/src/main/java/org/alfresco/web/action/evaluator/UploadNewVersionEvaluator.java deleted file mode 100644 index 54d20e2e24..0000000000 --- a/war/src/main/java/org/alfresco/web/action/evaluator/UploadNewVersionEvaluator.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.action.evaluator; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.web.bean.coci.EditOfflineDialog; -import org.alfresco.web.bean.repository.Node; - -/** - * UI Action Evaluator - Upload new version - */ -public class UploadNewVersionEvaluator extends BaseActionEvaluator -{ - /** - * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node) - */ - public boolean evaluate(Node node) - { - return (node.hasAspect(ContentModel.ASPECT_WORKING_COPY) && - EditOfflineDialog.OFFLINE_EDITING.equals(node.getProperties().get(ContentModel.PROP_WORKING_COPY_MODE)) && - node.hasPermission(PermissionService.CHECK_IN)); - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/app/AlfrescoNavigationHandler.java b/war/src/main/java/org/alfresco/web/app/AlfrescoNavigationHandler.java deleted file mode 100644 index 6dfea0050b..0000000000 --- a/war/src/main/java/org/alfresco/web/app/AlfrescoNavigationHandler.java +++ /dev/null @@ -1,1002 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app; - -import java.util.Stack; - -import javax.faces.application.NavigationHandler; -import javax.faces.application.ViewHandler; -import javax.faces.component.UIViewRoot; -import javax.faces.context.FacesContext; - -import org.springframework.extensions.config.Config; -import org.springframework.extensions.config.ConfigService; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.NavigationBean; -import org.alfresco.web.bean.dialog.DialogManager; -import org.alfresco.web.bean.dialog.DialogState; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.wizard.WizardManager; -import org.alfresco.web.bean.wizard.WizardState; -import org.alfresco.web.config.DialogsConfigElement; -import org.alfresco.web.config.NavigationConfigElement; -import org.alfresco.web.config.NavigationElementReader; -import org.alfresco.web.config.NavigationResult; -import org.alfresco.web.config.WizardsConfigElement; -import org.alfresco.web.config.DialogsConfigElement.DialogConfig; -import org.alfresco.web.config.WizardsConfigElement.WizardConfig; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * @author gavinc - */ -public class AlfrescoNavigationHandler extends NavigationHandler -{ - public final static String OUTCOME_SEPARATOR = ":"; - public final static String OUTCOME_BROWSE = "browse"; - public final static String DIALOG_PREFIX = "dialog" + OUTCOME_SEPARATOR; - public final static String WIZARD_PREFIX = "wizard" + OUTCOME_SEPARATOR; - public final static String CLOSE_DIALOG_OUTCOME = DIALOG_PREFIX + "close"; - public final static String CLOSE_WIZARD_OUTCOME = WIZARD_PREFIX + "close"; - public final static String CLOSE_MULTIPLE_START = "["; - public final static String CLOSE_MULTIPLE_END = "]"; - public final static String EXTERNAL_CONTAINER_SESSION = "externalDialogContainer"; - - protected String dialogContainer = null; - protected String wizardContainer = null; - protected String plainDialogContainer = null; - protected String plainWizardContainer = null; - - private final static Log logger = LogFactory.getLog(AlfrescoNavigationHandler.class); - private final static String VIEW_STACK = "_alfViewStack"; - - // The original navigation handler - private NavigationHandler origHandler; - - /** - * Default constructor - * - * @param origHandler The original navigation handler - */ - public AlfrescoNavigationHandler(NavigationHandler origHandler) - { - super(); - this.origHandler = origHandler; - } - - /** - * @see javax.faces.application.NavigationHandler#handleNavigation(javax.faces.context.FacesContext, java.lang.String, java.lang.String) - */ - @Override - @SuppressWarnings("unchecked") - public void handleNavigation(FacesContext context, String fromAction, String outcome) - { - if (logger.isDebugEnabled()) - { - logger.debug("handleNavigation (fromAction=" + fromAction + ", outcome=" + outcome + ")"); - logger.debug("Current view id: " + context.getViewRoot().getViewId()); - } - - boolean isDialog = isDialog(outcome); - if (isDialog || isWizard(outcome)) - { - boolean dialogWizardClosing = isDialogOrWizardClosing(outcome); - outcome = stripPrefix(outcome); - - if (dialogWizardClosing) - { - handleDialogOrWizardClose(context, fromAction, outcome, isDialog); - } - else - { - if (isDialog) - { - handleDialogOpen(context, fromAction, outcome); - } - else - { - handleWizardOpen(context, fromAction, outcome); - } - } - } - else - { - if (isWizardStep(fromAction)) - { - goToView(context, getWizardContainer(context)); - } - else - { - handleDispatch(context, fromAction, outcome); - } - } - - // reset the dispatch context - Object bean = FacesHelper.getManagedBean(context, NavigationBean.BEAN_NAME); - if (bean instanceof NavigationBean) - { - ((NavigationBean)bean).resetDispatchContext(); - } - - if (logger.isDebugEnabled()) - logger.debug("view stack: " + getViewStack(context)); - } - - /** - * Determines whether the given outcome is dialog related - * - * @param outcome The outcome to test - * @return true if outcome is dialog related i.e. starts with dialog: - */ - protected boolean isDialog(String outcome) - { - boolean dialog = false; - - if (outcome != null && outcome.startsWith(DIALOG_PREFIX)) - { - dialog = true; - } - - return dialog; - } - - /** - * Determines whether the given outcome is wizard related - * - * @param outcome The outcome to test - * @return true if outcome is wizard related - * i.e. starts with create-wizard: or edit-wizard: - */ - protected boolean isWizard(String outcome) - { - boolean wizard = false; - - if (outcome != null && outcome.startsWith(WIZARD_PREFIX)) - { - wizard = true; - } - - return wizard; - } - - /** - * Determines whether the given outcome represents a dialog or wizard closing - * - * @param outcome The outcome to test - * @return true if the outcome represents a closing dialog or wizard - */ - protected boolean isDialogOrWizardClosing(String outcome) - { - boolean closing = false; - - if (outcome != null && - (outcome.startsWith(CLOSE_DIALOG_OUTCOME) || - outcome.startsWith(CLOSE_WIZARD_OUTCOME))) - { - closing = true; - } - - return closing; - } - - protected int getNumberToClose(String outcome) - { - int toClose = 1; - - int idxStart = outcome.indexOf(CLOSE_MULTIPLE_START); - if (outcome != null && idxStart != -1) - { - int idxEnd = outcome.indexOf(CLOSE_MULTIPLE_END); - if (idxEnd != -1) - { - String closeNum = outcome.substring(idxStart+1, idxEnd); - try - { - toClose = Integer.parseInt(closeNum); - } - catch (NumberFormatException nfe) - { - if (logger.isWarnEnabled()) - logger.warn("Could not determine number of containers to close, defaulting to 1"); - } - } - - if (logger.isDebugEnabled()) - logger.debug("Closing " + toClose + " levels of container"); - } - - return toClose; - } - - /** - * Determines whether the given fromAction represents a step in the wizard - * i.e. next or back - * - * @param fromAction The fromAction - * @return true if the from action represents a wizard step - */ - protected boolean isWizardStep(String fromAction) - { - boolean wizardStep = false; - - if (fromAction != null && - (fromAction.equals("#{WizardManager.next}") || fromAction.equals("#{WizardManager.back}"))) - { - wizardStep = true; - } - - return wizardStep; - } - - /** - * Removes the dialog or wizard prefix from the given outcome - * - * @param outcome The outcome to remove the prefix from - * @return The remaining outcome - */ - protected String stripPrefix(String outcome) - { - String newOutcome = outcome; - - if (outcome != null) - { - int idx = outcome.indexOf(OUTCOME_SEPARATOR); - if (idx != -1) - { - newOutcome = outcome.substring(idx+1); - } - } - - return newOutcome; - } - - /** - * Returns the overridden outcome. - * Used by dialogs and wizards to go to a particular page after it closes - * rather than back to the page it was launched from. - * - * @param outcome The current outcome - * @return The overridden outcome or null if there isn't an override - */ - protected String getOutcomeOverride(String outcome) - { - String override = null; - - if (outcome != null) - { - int idx = outcome.indexOf(OUTCOME_SEPARATOR); - if (idx != -1) - { - override = outcome.substring(idx+1); - } - } - - return override; - } - - /** - * Returns the dialog configuration object for the given dialog name. - * If there is a node in the dispatch context a lookup is performed using - * the node otherwise the global config section is used. - * - * - * @param name The name of dialog being launched - * @param dispatchContext The node being acted upon - * @return The DialogConfig for the dialog or null if no config could be found - */ - protected DialogConfig getDialogConfig(FacesContext context, String name, Node dispatchContext) - { - DialogConfig dialogConfig = null; - ConfigService configSvc = Application.getConfigService(context); - - Config config = null; - - if (dispatchContext != null) - { - if (logger.isDebugEnabled()) - logger.debug("Using dispatch context for dialog lookup: " + - dispatchContext.getType().toString()); - - // use the node to perform the lookup (this will include the global section) - config = configSvc.getConfig(dispatchContext); - } - else - { - if (logger.isDebugEnabled()) - logger.debug("Looking up dialog in global config"); - - // just use the global - config = configSvc.getGlobalConfig(); - } - - if (config != null) - { - DialogsConfigElement dialogsCfg = (DialogsConfigElement)config.getConfigElement( - DialogsConfigElement.CONFIG_ELEMENT_ID); - if (dialogsCfg != null) - { - dialogConfig = dialogsCfg.getDialog(name); - } - } - - return dialogConfig; - } - - /** - * Returns the wizard configuration object for the given wizard name. - * If there is a node in the dispatch context a lookup is performed using - * the node otherwise the global config section is used. - * - * @param name The name of wizard being launched - * @param dispatchContext The node being acted upon - * @return The WizardConfig for the wizard or null if no config could be found - */ - protected WizardConfig getWizardConfig(FacesContext context, String name, Node dispatchContext) - { - WizardConfig wizardConfig = null; - ConfigService configSvc = Application.getConfigService(context); - - Config config = null; - - if (dispatchContext != null) - { - if (logger.isDebugEnabled()) - logger.debug("Using dispatch context for wizard lookup: " + - dispatchContext.getType().toString()); - - // use the node to perform the lookup (this will include the global section) - config = configSvc.getConfig(dispatchContext); - } - else - { - if (logger.isDebugEnabled()) - logger.debug("Looking up wizard in global config"); - - // just use the global - config = configSvc.getGlobalConfig(); - } - - if (config != null) - { - WizardsConfigElement wizardsCfg = (WizardsConfigElement)config.getConfigElement( - WizardsConfigElement.CONFIG_ELEMENT_ID); - if (wizardsCfg != null) - { - wizardConfig = wizardsCfg.getWizard(name); - } - } - - return wizardConfig; - } - - /** - * Retrieves the configured dialog container page - * - * @param context FacesContext - * @return The container page - */ - protected String getDialogContainer(FacesContext context) - { - String container; - - // determine which kind of container we need to return, if the - // external session flag is set then use the plain container - Object obj = context.getExternalContext().getSessionMap().get(EXTERNAL_CONTAINER_SESSION); - - if (obj != null && obj instanceof Boolean && ((Boolean)obj).booleanValue()) - { - if ((this.plainDialogContainer == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - ConfigService configSvc = Application.getConfigService(context); - Config globalConfig = configSvc.getGlobalConfig(); - - if (globalConfig != null) - { - this.plainDialogContainer = globalConfig.getConfigElement("plain-dialog-container").getValue(); - } - } - - container = this.plainDialogContainer; - } - else - { - if ((this.dialogContainer == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - ConfigService configSvc = Application.getConfigService(context); - Config globalConfig = configSvc.getGlobalConfig(); - - if (globalConfig != null) - { - this.dialogContainer = globalConfig.getConfigElement("dialog-container").getValue(); - } - } - - container = this.dialogContainer; - } - - if (logger.isDebugEnabled()) - logger.debug("Using dialog container: " + container); - - return container; - } - - /** - * Retrieves the configured wizard container page - * - * @param context FacesContext - * @return The container page - */ - protected String getWizardContainer(FacesContext context) - { - String container; - - // determine which kind of container we need to return, if the - // external session flag is set then use the plain container - Object obj = context.getExternalContext().getSessionMap().get(EXTERNAL_CONTAINER_SESSION); - - if (obj != null && obj instanceof Boolean && ((Boolean)obj).booleanValue()) - { - if ((this.plainWizardContainer == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - ConfigService configSvc = Application.getConfigService(context); - Config globalConfig = configSvc.getGlobalConfig(); - - if (globalConfig != null) - { - this.plainWizardContainer = globalConfig.getConfigElement("plain-wizard-container").getValue(); - } - } - - container = this.plainWizardContainer; - } - else - { - if ((this.wizardContainer == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - ConfigService configSvc = Application.getConfigService(context); - Config globalConfig = configSvc.getGlobalConfig(); - - if (globalConfig != null) - { - this.wizardContainer = globalConfig.getConfigElement("wizard-container").getValue(); - } - } - - container = this.wizardContainer; - } - - if (logger.isDebugEnabled()) - logger.debug("Using wizard container: " + container); - - return container; - } - - /** - * Returns the node currently in the dispatch context - * - * @return The node currently in the dispatch context or null if - * the dispatch context is empty - */ - protected Node getDispatchContextNode(FacesContext context) - { - Node dispatchNode = null; - - NavigationBean navBean = (NavigationBean)context.getExternalContext(). - getSessionMap().get(NavigationBean.BEAN_NAME); - - if (navBean != null) - { - dispatchNode = navBean.getDispatchContextNode(); - } - - return dispatchNode; - } - - protected void handleBrowseDispatch(FacesContext context, String fromAction, String outcome) - { - Node dispatchNode = null; - - NavigationBean navBean = (NavigationBean) context.getExternalContext().getSessionMap() - .get(NavigationBean.BEAN_NAME); - - if (navBean != null) - { - dispatchNode = navBean.getCurrentNode(); - } - - handleDispatch(context, fromAction, outcome, dispatchNode); - } - - /** - * Processes any dispatching that may need to occur - * - * @param context Faces context - * @param fromAction The from action - * @param outcome The outcome - */ - protected void handleDispatch(FacesContext context, String fromAction, String outcome) - { - Node dispatchNode = getDispatchContextNode(context); - handleDispatch(context, fromAction, outcome, dispatchNode); - } - - private void handleDispatch(FacesContext context, String fromAction, String outcome, Node dispatchNode) - { - if (dispatchNode != null) - { - if (logger.isDebugEnabled()) - logger.debug("Found node with type '" + dispatchNode.getType().toString() + - "' in dispatch context"); - - // get the current view id - String viewId = context.getViewRoot().getViewId(); - - // see if there is any navigation config for the node type - ConfigService configSvc = Application.getConfigService(context); - NavigationConfigElement navigationCfg = null; - try - { - Config nodeConfig = configSvc.getConfig(dispatchNode); - navigationCfg = (NavigationConfigElement)nodeConfig. - getConfigElement(NavigationElementReader.ELEMENT_NAVIGATION); - } - catch (InvalidNodeRefException e) - { - if (logger.isDebugEnabled()) logger.debug("Invalid node reference: " + dispatchNode); - } - - if (navigationCfg != null) - { - // see if there is config for the current view state - NavigationResult navResult = navigationCfg.getOverride(viewId, outcome); - - if (navResult != null) - { - if (logger.isDebugEnabled()) - logger.debug("Found navigation config: " + navResult); - - if (navResult.isOutcome()) - { - navigate(context, fromAction, navResult.getResult()); - } - else - { - String newViewId = navResult.getResult(); - - if (newViewId.equals(viewId) == false) - { - if (logger.isDebugEnabled()) - logger.debug("Dispatching to new view id: " + newViewId); - - goToView(context, newViewId); - } - else - { - if (logger.isDebugEnabled()) - logger.debug("New view id is the same as the current one so setting outcome to null"); - - navigate(context, fromAction, null); - } - } - } - else - { - if (logger.isDebugEnabled()) - logger.debug("No override configuration found for current view or outcome"); - - navigate(context, fromAction, outcome); - } - } - else - { - if (logger.isDebugEnabled()) - logger.debug("No navigation configuration found for node"); - - navigate(context, fromAction, outcome); - } - - // reset the dispatch context - ((NavigationBean)context.getExternalContext().getSessionMap(). - get(NavigationBean.BEAN_NAME)).resetDispatchContext(); - } - else - { - if (logger.isDebugEnabled()) - logger.debug("No dispatch context found"); - - // pass off to the original handler - navigate(context, fromAction, outcome); - } - } - - /** - * Opens a dialog - * - * @param context FacesContext - * @param fromAction The fromAction - * @param name The name of the dialog to open - */ - protected void handleDialogOpen(FacesContext context, String fromAction, String name) - { - if (logger.isDebugEnabled()) - logger.debug("Opening dialog '" + name + "'"); - - // firstly add the current view to the stack so we know where to go back to - addCurrentViewToStack(context); - - DialogConfig config = getDialogConfig(context, name, getDispatchContextNode(context)); - if (config != null) - { - if (logger.isDebugEnabled()) - logger.debug("Found config for dialog '" + name + "': " + config); - - // set the dialog manager up with the retrieved config - DialogManager dialogManager = Application.getDialogManager(); - dialogManager.setCurrentDialog(config); - - // retrieve the container page and navigate to it - goToView(context, getDialogContainer(context)); - } - else - { - //logger.warn("Failed to find configuration for dialog '" + name + "'"); - - // send the dialog name as the outcome to the original handler - handleDispatch(context, fromAction, name); - } - } - - /** - * Opens a wizard - * - * @param context FacesContext - * @param fromAction The fromAction - * @param name The name of the wizard to open - */ - protected void handleWizardOpen(FacesContext context, String fromAction, String name) - { - if (logger.isDebugEnabled()) - logger.debug("Opening wizard '" + name + "'"); - - // firstly add the current view to the stack so we know where to go back to - addCurrentViewToStack(context); - - WizardConfig wizard = getWizardConfig(context, name, getDispatchContextNode(context)); - if (wizard != null) - { - if (logger.isDebugEnabled()) - logger.debug("Found config for wizard '" + name + "': " + wizard); - - // set the wizard manager up with the retrieved config - WizardManager wizardManager = Application.getWizardManager(); - wizardManager.setCurrentWizard(wizard); - - // retrieve the container page and navigate to it - goToView(context, getWizardContainer(context)); - } - else - { - //logger.warn("Failed to find configuration for wizard '" + name + "'"); - - // send the dialog name as the outcome to the original handler - handleDispatch(context, fromAction, name); - } - } - - /** - * Closes the current dialog or wizard - * - * @param context FacesContext - * @param fromAction The fromAction - * @param outcome The outcome - * @param dialog true if a dialog is being closed, false if a wizard is being closed - */ - protected void handleDialogOrWizardClose(FacesContext context, String fromAction, String outcome, boolean dialog) - { - String closingItem = dialog ? "dialog" : "wizard"; - - // if we are closing a wizard or dialog take the view off the - // top of the stack then decide whether to use the view - // or any overridden outcome that may be present - if (getViewStack(context).empty() == false) - { - // is there an overidden outcome? - String overriddenOutcome = getOutcomeOverride(outcome); - if (overriddenOutcome == null) - { - // there isn't an overidden outcome so go back to the previous view - if (logger.isDebugEnabled()) - logger.debug("Closing " + closingItem); - - // determine how many levels of dialog we need to close - int numberToClose = getNumberToClose(outcome); - - Object stackObject = null; - if (numberToClose == 1) - { - // just closing one dialog so get the item from the top of the stack - stackObject = getViewStack(context).pop(); - - if (logger.isDebugEnabled()) - logger.debug("Popped item from the top of the view stack: " + stackObject); - } - else - { - // check there are enough items on the stack, if there - // isn't just get the last one (effectively going back - // to the beginning) - Stack viewStack = getViewStack(context); - int itemsOnStack = viewStack.size(); - if (itemsOnStack < numberToClose) - { - if (logger.isDebugEnabled()) - logger.debug("Returning to first item on the view stack as there aren't " + - numberToClose + " containers to close!"); - - numberToClose = itemsOnStack; - } - - // pop the right object from the stack - for (int x = 1; x <= numberToClose; x++) - { - stackObject = viewStack.pop(); - } - - if (logger.isDebugEnabled()) - logger.debug("Popped item from the stack: " + stackObject); - } - - // get the appropriate view id for the stack object - String newViewId = getViewIdFromStackObject(context, stackObject); - - // go to the appropraite page - goToView(context, newViewId); - } - else - { - // we also need to empty the dialog stack if we have been given - // an overidden outcome as we could be going anywhere in the app. - // grab the current top item first though in case we need to open - // another dialog or wizard - if (OUTCOME_BROWSE.equals(overriddenOutcome) == false) - { - String previousViewId = getViewIdFromStackObject(context, getViewStack(context).peek()); - getViewStack(context).clear(); - - if (logger.isDebugEnabled()) - logger.debug("Closing " + closingItem + " with an overridden outcome of '" + overriddenOutcome + "'"); - - // if the override is calling another dialog or wizard come back through - // the navigation handler from the beginning - if (isDialog(overriddenOutcome) || isWizard(overriddenOutcome)) - { - // set the view id to the page at the top of the stack so when - // the new dialog or wizard closes it goes back to the correct page - context.getViewRoot().setViewId(previousViewId); - - if (logger.isDebugEnabled()) - { - logger.debug("view stack: " + getViewStack(context)); - logger.debug("Opening '" + overriddenOutcome + "' after " + closingItem + - " close using view id: " + previousViewId); - } - - this.handleNavigation(context, fromAction, overriddenOutcome); - } - else - { - navigate(context, fromAction, overriddenOutcome); - } - } - else - { - handleBrowseDispatch(context, fromAction, overriddenOutcome); - - // ALF-6661, always clear the view stack with an overridden outcome - getViewStack(context).clear(); - } - } - } - else - { - // we are trying to close a dialog when one hasn't been opened! - // return to the main page of the app (print warning if debug is enabled) - if (logger.isDebugEnabled()) - { - logger.debug("Attempting to close a " + closingItem + " with an empty view stack, returning 'browse' outcome"); - } - - navigate(context, fromAction, OUTCOME_BROWSE); - } - } - - /** - * Returns the view id of the given item retrieved from the view stack. - * - * @param context FacesContext - * @param topOfStack The object retrieved from the view stack - * @return The view id - */ - protected String getViewIdFromStackObject(FacesContext context, Object topOfStack) - { - String viewId = null; - - // if the top of the stack is not a dialog or wizard just get the - // view id and navigate back to it. - - // if the top of the stack is a dialog or wizard retrieve the state - // and setup the appropriate manager with that state, then get the - // appropriate container page and navigate to it. - - if (topOfStack instanceof String) - { - viewId = (String)topOfStack; - } - else if (topOfStack instanceof DialogState) - { - // restore the dialog state and get the dialog container viewId - Application.getDialogManager().restoreState((DialogState)topOfStack); - viewId = getDialogContainer(context); - } - else if (topOfStack instanceof WizardState) - { - // restore the wizard state and get the wizard container viewId - Application.getWizardManager().restoreState((WizardState)topOfStack); - viewId = getWizardContainer(context); - } - else - { - if (logger.isWarnEnabled()) - logger.warn("Invalid object found on view stack: " + topOfStack); - } - - return viewId; - } - - /** - * Adds the current view to the stack (if required). - * If the current view is already the top of the stack it is not added again - * to stop the stack from growing and growing. - * - * @param context FacesContext - */ - @SuppressWarnings("unchecked") - protected void addCurrentViewToStack(FacesContext context) - { - // if the current viewId is either the dialog or wizard container page - // we need to save the state of the current dialog or wizard to the stack - - // If the current view is a normal page and it is not the same as the - // view currently at the top of the stack (you can't launch a dialog from - // the same page 2 times in a row so it must mean the user navigated away - // from the first dialog) just add the viewId to the stack - - // work out what to add to the stack - String viewId = context.getViewRoot().getViewId(); - String dialogContainer = getDialogContainer(context); - String wizardContainer = getWizardContainer(context); - Object objectForStack = null; - if (viewId.equals(dialogContainer)) - { - DialogManager dlgMgr = Application.getDialogManager(); - objectForStack = dlgMgr.getState(); - } - else if (viewId.equals(wizardContainer)) - { - WizardManager wizMgr = Application.getWizardManager(); - objectForStack = wizMgr.getState(); - } - else - { - objectForStack = viewId; - } - - // if the stack is currently empty add the item - Stack stack = getViewStack(context); - if (stack.empty()) - { - stack.push(objectForStack); - - if (logger.isDebugEnabled()) - logger.debug("Pushed item to view stack: " + objectForStack); - } - else - { - // if the item to go on to the stack and the top of - // stack are both Strings and equals to each other - // don't add anything to the stack to stop it - // growing unecessarily - Object topOfStack = stack.peek(); - if (objectForStack instanceof String && - topOfStack instanceof String && - topOfStack.equals(objectForStack)) - { - if (logger.isDebugEnabled()) - logger.debug("current view is already top of the view stack!"); - } - else - { - stack.push(objectForStack); - - if (logger.isDebugEnabled()) - logger.debug("Pushed item to view stack: " + objectForStack); - } - } - } - - /** - * Navigates to the appropriate page using the original navigation handler - * - * @param context FacesContext - * @param fromAction The fromAction - * @param outcome The outcome - */ - private void navigate(FacesContext context, String fromAction, String outcome) - { - if (logger.isDebugEnabled()) - logger.debug("Passing outcome '" + outcome + "' to original navigation handler"); - - this.origHandler.handleNavigation(context, fromAction, outcome); - } - - /** - * Dispatches to the given view id - * - * @param context Faces context - * @param viewId The view id to go to - */ - private void goToView(FacesContext context, String viewId) - { - ViewHandler viewHandler = context.getApplication().getViewHandler(); - UIViewRoot viewRoot = viewHandler.createView(context, viewId); - viewRoot.setViewId(viewId); - context.setViewRoot(viewRoot); - context.renderResponse(); - } - - /** - * Returns the view stack for the current user. - * - * @param context FacesContext - * @return A Stack representing the views that have launched dialogs in - * the users session, will never be null - */ - @SuppressWarnings("unchecked") - private Stack getViewStack(FacesContext context) - { - Stack viewStack = (Stack)context.getExternalContext().getSessionMap().get(VIEW_STACK); - - if (viewStack == null) - { - viewStack = new Stack(); - context.getExternalContext().getSessionMap().put(VIEW_STACK, viewStack); - } - - return viewStack; - } -} diff --git a/war/src/main/java/org/alfresco/web/app/Application.java b/war/src/main/java/org/alfresco/web/app/Application.java deleted file mode 100644 index 6c14240966..0000000000 --- a/war/src/main/java/org/alfresco/web/app/Application.java +++ /dev/null @@ -1,1258 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app; - -import java.io.IOException; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Properties; -import java.util.ResourceBundle; - -import javax.faces.context.FacesContext; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.alfresco.repo.SessionUser; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.repo.importer.ImporterBootstrap; -import org.alfresco.service.cmr.repository.StoreRef; -import org.alfresco.service.cmr.security.AuthenticationService; -import org.alfresco.web.app.portlet.AlfrescoFacesPortlet; -import org.alfresco.web.app.servlet.AuthenticationHelper; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.ErrorBean; -import org.alfresco.web.bean.SidebarBean; -import org.alfresco.web.bean.dashboard.DashboardManager; -import org.alfresco.web.bean.dialog.DialogManager; -import org.alfresco.web.bean.repository.PreferencesService; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.repository.User; -import org.alfresco.web.bean.users.UserPreferencesBean; -import org.alfresco.web.bean.wizard.WizardManager; -import org.alfresco.web.config.ClientConfigElement; -import org.alfresco.web.config.LanguagesConfigElement; -import org.apache.commons.logging.Log; -import org.springframework.context.ApplicationContext; -import org.springframework.extensions.config.Config; -import org.springframework.extensions.config.ConfigService; -import org.springframework.extensions.surf.util.I18NUtil; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.WebApplicationContextUtils; -import org.springframework.web.jsf.FacesContextUtils; - -/** - * Utilities class - * - * @author gavinc - */ -public class Application -{ - private static final String LOCALE = "locale"; - private static final String USE_SESSION_LOCALE = "USE_SESSION_LOCALE"; - - public static final String BEAN_CONFIG_SERVICE = "webClientConfigService"; - public static final String BEAN_DATA_DICTIONARY = "dataDictionary"; - public static final String BEAN_IMPORTER_BOOTSTRAP = "spacesBootstrap"; - private static final String BEAN_UNPROTECTED_AUTH_SERVICE = "authenticationService"; - - public static final String MESSAGE_BUNDLE = "alfresco.messages.webclient"; - - private static ThreadLocal inPortalServer = new ThreadLocal(); - private static StoreRef repoStoreRef; - private static String rootPath; - private static String companyRootId; - private static String glossaryFolderName; - private static String spaceTemplatesFolderName; - private static String contentTemplatesFolderName; - private static String emailTemplatesFolderName; - private static String inviteEmailTemplatesFolderName; - private static String notifyEmailTemplatesFolderName; - private static String rssTemplatesFolderName; - private static String savedSearchesFolderName; - private static String scriptsFolderName; - private static String guestHomeFolderName; - private static String websitesFolderName; - private static String webContentFormsFolderName; - private static String contentFormsFolderName; - private static String projectsFolderName; - - private static Boolean isDynamicConfig = null; - - - /** - * Private constructor to prevent instantiation of this class - */ - private Application() - { - } - - /** - * Sets whether this application is running inside a portal server - * - * @param inPortal true to indicate the application is running as a portlet - */ - public static void setInPortalServer(boolean inPortal) - { - inPortalServer.set(inPortal ? Boolean.TRUE : null); - } - - /** - * Determines whether the server is running in a portal - * - * @return true if we are running inside a portal server - */ - public static boolean inPortalServer() - { - Boolean result = inPortalServer.get(); - return result == null ? false : result; - } - - /** - * Handles errors thrown from servlets - * - * @param servletContext The servlet context - * @param request The HTTP request - * @param response The HTTP response - * @param error The exception - * @param logger The logger - */ - public static void handleServletError(ServletContext servletContext, HttpServletRequest request, - HttpServletResponse response, Throwable error, Log logger, String returnPage) - throws IOException, ServletException - { - // get the error bean from the session and set the error that occurred. - HttpSession session = request.getSession(); - ErrorBean errorBean = (ErrorBean)session.getAttribute(ErrorBean.ERROR_BEAN_NAME); - if (errorBean == null) - { - errorBean = new ErrorBean(); - session.setAttribute(ErrorBean.ERROR_BEAN_NAME, errorBean); - } - errorBean.setLastError(error); - errorBean.setReturnPage(returnPage); - - // try and find the configured error page - boolean errorShown = false; - String errorPage = getErrorPage(servletContext); - - if (errorPage != null) - { - if (logger.isDebugEnabled()) - logger.debug("An error has occurred, redirecting to error page: " + errorPage); - - if (response.isCommitted() == false) - { - errorShown = true; - response.sendRedirect(request.getContextPath() + errorPage); - } - else - { - if (logger.isDebugEnabled()) - logger.debug("Response is already committed, re-throwing error"); - } - } - else - { - if (logger.isDebugEnabled()) - logger.debug("No error page defined, re-throwing error"); - } - - // if we could not show the error page for whatever reason, re-throw the error - if (!errorShown) - { - if (error instanceof IOException) - { - throw (IOException)error; - } - else if (error instanceof ServletException) - { - throw (ServletException)error; - } - else - { - throw new ServletException(error); - } - } - } - - /** - * Handles error conditions detected by servlets. - * - * @param servletContext - * The servlet context - * @param request - * The HTTP request - * @param response - * The HTTP response - * @param messageKey - * the resource bundle key for the error mesage - * @param statusCode - * the status code to set on the response - * @param logger - * The logger - * @throws IOException - * Signals that an I/O exception has occurred. - * @throws ServletException - * the servlet exception - */ - public static void handleSystemError(ServletContext servletContext, HttpServletRequest request, - HttpServletResponse response, String messageKey, int statusCode, Log logger) - throws IOException, ServletException - { - // get the error bean from the session and set the error that occurred. - HttpSession session = request.getSession(); - ErrorBean errorBean = (ErrorBean)session.getAttribute(ErrorBean.ERROR_BEAN_NAME); - if (errorBean == null) - { - errorBean = new ErrorBean(); - session.setAttribute(ErrorBean.ERROR_BEAN_NAME, errorBean); - } - errorBean.setErrorMessageKey(messageKey); - errorBean.setReturnPage(null); - - // try and find the configured error page - boolean errorShown = false; - String errorPage = getErrorPage(servletContext); - - if (errorPage != null) - { - if (logger.isDebugEnabled()) - logger.debug("An error has occurred, forwarding to error page: " + errorPage); - - if (!response.isCommitted()) - { - errorShown = true; - response.reset(); - response.setStatus(statusCode); - response.setContentType(MimetypeMap.MIMETYPE_HTML); - response.setCharacterEncoding("utf-8"); - servletContext.getRequestDispatcher(errorPage).include(request, response); - } - else - { - if (logger.isDebugEnabled()) - logger.debug("Response is already committed, re-throwing error"); - } - } - else - { - if (logger.isDebugEnabled()) - logger.debug("No error page defined, re-throwing error"); - } - - // if we could not show the error page for whatever reason, re-throw the error - if (!errorShown) - { - throw new ServletException(getMessage(session, messageKey)); - } - } - - /** - * Retrieves the DialogManager managed bean - * - * @return DialogManager bean - */ - public static DialogManager getDialogManager() - { - return (DialogManager)FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), DialogManager.BEAN_NAME); - } - - /** - * Retrieves the WizardManager managed bean - * - * @return WizardManager bean - */ - public static WizardManager getWizardManager() - { - return (WizardManager)FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), WizardManager.BEAN_NAME); - } - - /** - * Retrieves the DashboardManager managed bean - * - * @return DashboardManager bean - */ - public static DashboardManager getDashboardManager() - { - return (DashboardManager)FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), DashboardManager.BEAN_NAME); - } - - /** - * Retrieves the SidebarBean - * - * @return SidebarBean bean - */ - public static SidebarBean getSidebarBean() - { - return (SidebarBean)FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), "SidebarBean"); - } - - /** - * Retrieves the configured error page for the application - * - * @param servletContext The servlet context - * @return The configured error page or null if the configuration is missing - */ - public static String getErrorPage(ServletContext servletContext) - { - return getErrorPage(WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)); - } - - /** - * Retrieves the configured login page for the application - * - * @param servletContext The servlet context - * @return The configured login page or null if the configuration is missing - */ - public static String getLoginPage(ServletContext servletContext) - { - return getLoginPage(WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)); - } - - /** - * @return Returns the User object representing the currently logged in user - */ - public static User getCurrentUser(HttpSession session) - { - return (User)session.getAttribute(AuthenticationHelper.AUTHENTICATION_USER); - } - - /** - * @return Returns the User object representing the currently logged in user - */ - public static User getCurrentUser(FacesContext context) - { - if (inPortalServer()) - { - User user = (User) AlfrescoFacesPortlet.getPortletSessionAttribute(context, - AuthenticationHelper.AUTHENTICATION_USER, true); - if (user != null) - { - return user; - } - } - return (User) context.getExternalContext().getSessionMap().get(AuthenticationHelper.AUTHENTICATION_USER); - } - - public static void setCurrentUser(FacesContext context, User user) - { - if (inPortalServer()) - { - AlfrescoFacesPortlet.setPortletSessionAttribute(context, AuthenticationHelper.AUTHENTICATION_USER, user, true); - } - else - { - context.getExternalContext().getSessionMap().put(AuthenticationHelper.AUTHENTICATION_USER, user); - } - } - - /** - * Invalidate Alfresco ticket and Web/Portlet session and clear the Security context for this thread. - * @param context - */ - public static void logOut(FacesContext context) - { - String ticket = null; - if (Application.inPortalServer()) - { - ticket = AlfrescoFacesPortlet.onLogOut(context.getExternalContext().getRequest()); - } - else - { - SessionUser user = getCurrentUser(context); - if (user != null) - { - ticket = user.getTicket(); - } - HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest(); - HttpSession session = request.getSession(false); - if (session != null) - { - session.invalidate(); - } - } - - // Explicitly invalidate the Alfresco ticket. This no longer happens on session expiry to allow for ticket - // 'sharing' - WebApplicationContext wc = FacesContextUtils.getRequiredWebApplicationContext(context); - AuthenticationService unprotAuthService = (AuthenticationService) wc.getBean(BEAN_UNPROTECTED_AUTH_SERVICE); - if (ticket != null) - { - unprotAuthService.invalidateTicket(ticket); - } - unprotAuthService.clearCurrentSecurityContext(); - } - - /** - * @return Returns the repository store URL (retrieved from config service) - */ - public static StoreRef getRepositoryStoreRef(ServletContext context) - { - return getRepositoryStoreRef(WebApplicationContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Returns the repository store URL (retrieved from config service) - */ - public static StoreRef getRepositoryStoreRef(FacesContext context) - { - return getRepositoryStoreRef(FacesContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Returns id of the company root - * - * @deprecated Replace with user-context-specific getCompanyRootId (e.g. could be tenant-specific) - */ - public static String getCompanyRootId() - { - return companyRootId; - } - - /** - * Sets the company root id. This is setup by the ContextListener. - * - * @param id The company root id - * - * @deprecated Replace with user-context-specific getCompanyRootId (e.g. could be tenant-specific) - */ - public static void setCompanyRootId(String id) - { - companyRootId = id; - } - - /** - * @return Returns id of the company root - */ - public static String getCompanyRootId(FacesContext context) - { - User user = Application.getCurrentUser(context); - if (user != null) - { - String userCompanyRootId = user.getCompanyRootId(); - if (userCompanyRootId == null) - { - userCompanyRootId = Repository.getCompanyRoot(context).getId(); - user.setCompanyRootId(userCompanyRootId); - } - - return userCompanyRootId; - } - else - { - return null; - } - } - - /** - * @return Returns the root path for the application - */ - public static String getRootPath(ServletContext context) - { - return getRootPath(WebApplicationContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Returns the root path for the application - */ - public static String getRootPath(FacesContext context) - { - return getRootPath(FacesContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Returns the glossary folder name - */ - public static String getGlossaryFolderName(ServletContext context) - { - return getGlossaryFolderName(WebApplicationContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Returns the glossary folder name - */ - public static String getGlossaryFolderName(FacesContext context) - { - return getGlossaryFolderName(FacesContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Returns the Space templates folder name - */ - public static String getSpaceTemplatesFolderName(ServletContext context) - { - return getSpaceTemplatesFolderName(WebApplicationContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Returns the Space templates folder name - */ - public static String getSpaceTemplatesFolderName(FacesContext context) - { - return getSpaceTemplatesFolderName(FacesContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Returns the Content templates folder name - */ - public static String getContentTemplatesFolderName(ServletContext context) - { - return getContentTemplatesFolderName(WebApplicationContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Returns the Content templates folder name - */ - public static String getContentTemplatesFolderName(FacesContext context) - { - return getContentTemplatesFolderName(FacesContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Returns the Invite Email Templates folder name - */ - public static String getInviteEmailTemplatesFolderName(ServletContext context) - { - return getInviteEmailTemplatesFolderName(WebApplicationContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Returns the Invite Email Templates folder name - */ - public static String getInviteEmailTemplatesFolderName(FacesContext context) - { - return getInviteEmailTemplatesFolderName(FacesContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Returns the Notify Email Templates folder name - */ - public static String getNotifyEmailTemplatesFolderName(ServletContext context) - { - return getNotifyEmailTemplatesFolderName(WebApplicationContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Returns the Notify Email Templates folder name - */ - public static String getNotifyEmailTemplatesFolderName(FacesContext context) - { - return getNotifyEmailTemplatesFolderName(FacesContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Returns the Email templates folder name - */ - public static String getEmailTemplatesFolderName(ServletContext context) - { - return getEmailTemplatesFolderName(WebApplicationContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Returns the Email templates folder name - */ - public static String getEmailTemplatesFolderName(FacesContext context) - { - return getEmailTemplatesFolderName(FacesContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Returns the RSS templates folder name - */ - public static String getRSSTemplatesFolderName(ServletContext context) - { - return getRSSTemplatesFolderName(WebApplicationContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Returns the RSS templates folder name - */ - public static String getRSSTemplatesFolderName(FacesContext context) - { - return getRSSTemplatesFolderName(FacesContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Return the Saved Searches folder name - */ - public static String getSavedSearchesFolderName(ServletContext context) - { - return getSavedSearchesFolderName(WebApplicationContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Return the Saved Searches folder name - */ - public static String getSavedSearchesFolderName(FacesContext context) - { - return getSavedSearchesFolderName(FacesContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Return the JavaScript scripts folder name - */ - public static String getScriptsFolderName(ServletContext context) - { - return getScriptsFolderName(WebApplicationContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Return the JavaScript scripts folder name - */ - public static String getScriptsFolderName(FacesContext context) - { - return getScriptsFolderName(FacesContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Return the Guest Home folder name - */ - public static String getGuestHomeFolderName(ServletContext context) - { - return getGuestHomeFolderName(WebApplicationContextUtils.getRequiredWebApplicationContext(context)); - } - - /** - * @return Return the Guest Home folder name - */ - public static String getGuestHomeFolderName(FacesContext context) - { - return getGuestHomeFolderName(FacesContextUtils.getRequiredWebApplicationContext(context)); - } - - - /** - * Set the language locale for the current user context - * - * @param context FacesContext for current user - * @param code The ISO locale code to set - */ - @SuppressWarnings("unchecked") - public static void setLanguage(FacesContext context, String code) - { - Locale locale = I18NUtil.parseLocale(code); - - // set locale for JSF framework usage - context.getViewRoot().setLocale(locale); - - // set locale for our framework usage - context.getExternalContext().getSessionMap().put(LOCALE, locale); - - // clear the current message bundle - so it's reloaded with new locale - context.getExternalContext().getSessionMap().remove(MESSAGE_BUNDLE); - context.getExternalContext().getSessionMap().put(USE_SESSION_LOCALE, Boolean.TRUE); - - // Set the current locale in the server thread - I18NUtil.setLocale(locale); - } - - /** - * Set the language locale for the current user session. - * - * @param session HttpSession for current user - * @param code The ISO locale code to set - */ - @Deprecated - public static void setLanguage(HttpSession session, String code) - { - Locale locale = I18NUtil.parseLocale(code); - - session.setAttribute(LOCALE, locale); - session.removeAttribute(MESSAGE_BUNDLE); - session.setAttribute(USE_SESSION_LOCALE, Boolean.TRUE); - - // Set the current locale in the server thread - I18NUtil.setLocale(locale); - } - - /** - * Return the language Locale for the current user context - * - * @param fc FacesContext for the current user - * - * @return Current language Locale set or the VM default if none set - never null - */ - public static Locale getLanguage(FacesContext fc) - { - boolean useInterfaceLanguage = Application.getClientConfig(fc).isLanguageSelect(); - Map sessionMap = fc.getExternalContext().getSessionMap(); - Boolean useSessionLocale = (Boolean)sessionMap.get(USE_SESSION_LOCALE); - if (useSessionLocale == null) - { - useSessionLocale = Boolean.TRUE; - sessionMap.put(USE_SESSION_LOCALE, useSessionLocale); - } - Locale locale = (Locale)sessionMap.get(LOCALE); - if (locale == null || (!locale.equals(I18NUtil.getLocale()) && !useInterfaceLanguage)) - { - if (useSessionLocale && useInterfaceLanguage) - { - // first check saved user preferences - String strLocale = null; - if (getCurrentUser(fc) != null) - { - strLocale = (String)PreferencesService.getPreferences(fc).getValue( - UserPreferencesBean.PREF_INTERFACELANGUAGE); - if (strLocale != null) - { - locale = I18NUtil.parseLocale(strLocale); - } - else - { - // failing that, use the server default locale - locale = Locale.getDefault(); - } - } - else - { - // else get from web-client config - the first item in the configured list of languages - Config config = Application.getConfigService(fc).getConfig("Languages"); - LanguagesConfigElement langConfig = (LanguagesConfigElement)config.getConfigElement( - LanguagesConfigElement.CONFIG_ELEMENT_ID); - List languages = langConfig.getLanguages(); - if (languages != null && languages.size() != 0) - { - locale = I18NUtil.parseLocale(languages.get(0)); - } - else - { - // failing that, use the server default locale - locale = Locale.getDefault(); - } - } - // save in user session - sessionMap.put(LOCALE, locale); - } - else - { - // Get the request default, already decoded from the request headers - locale = I18NUtil.getLocale(); - } - } - return locale; - } - - /** - * Return the language Locale for the current user Session. - * - * @param session - * HttpSession for the current user - * @param useInterfaceLanguage - * If the session language hasn't been established yet, should we base it on user preferences? - * @return Current language Locale set or the VM default if none set - never null - */ - public static Locale getLanguage(HttpSession session, boolean useInterfaceLanguage) - { - Boolean useSessionLocale = (Boolean)session.getAttribute(USE_SESSION_LOCALE); - if (useSessionLocale == null) - { - useSessionLocale = useInterfaceLanguage; - session.setAttribute(USE_SESSION_LOCALE, useSessionLocale); - } - Locale locale = (Locale)session.getAttribute(LOCALE); - if (locale == null || (!locale.equals(I18NUtil.getLocale()) && !useInterfaceLanguage)) - { - if (useSessionLocale && useInterfaceLanguage) - { - // first check saved user preferences - String strLocale = null; - if (getCurrentUser(session) != null) - { - strLocale = (String) PreferencesService.getPreferences(session).getValue( - UserPreferencesBean.PREF_INTERFACELANGUAGE); - if (strLocale != null) - { - locale = I18NUtil.parseLocale(strLocale); - } - else - { - // failing that, use the server default locale - locale = Locale.getDefault(); - } - } - else - { - // else get from web-client config - the first item in the configured list of languages - locale = getLanguage(WebApplicationContextUtils.getRequiredWebApplicationContext(session - .getServletContext())); - - } - - // This is an interface session - the same locale will be used for the rest of the session - session.setAttribute(LOCALE, locale); - } - else - { - // Get the request default, already decoded from the request headers - locale = I18NUtil.getLocale(); - } - } - return locale; - } - - /** - * Return the configured language Locale for the application context - * - * @param ctx - * the application context - * @return Current language Locale set or the VM default if none set - never null - */ - public static Locale getLanguage(ApplicationContext ctx) - { - // get from web-client config - the first item in the configured list of languages - Config config = ((ConfigService) ctx.getBean(Application.BEAN_CONFIG_SERVICE)).getConfig("Languages"); - LanguagesConfigElement langConfig = (LanguagesConfigElement) config - .getConfigElement(LanguagesConfigElement.CONFIG_ELEMENT_ID); - List languages = langConfig.getLanguages(); - if (languages != null && languages.size() != 0) - { - return I18NUtil.parseLocale(languages.get(0)); - } - else - { - // failing that, use the server default locale - return Locale.getDefault(); - } - } - - /** - * Get the specified I18N message string from the default message bundle for this user - * - * @param context FacesContext - * @param msg Message ID - * - * @return String from message bundle or $$msg$$ if not found - */ - public static String getMessage(FacesContext context, String msg) - { - return getBundle(context).getString(msg); - } - - /** - * Get the specified I18N message string from the default message bundle for this user - * - * @param session HttpSession - * @param msg Message ID - * - * @return String from message bundle or $$msg$$ if not found - */ - public static String getMessage(HttpSession session, String msg) - { - return getBundle(session).getString(msg); - } - - /** - * Get the specified the default message bundle for this user - * - * @param session HttpSession - * - * @return ResourceBundle for this user - */ - public static ResourceBundle getBundle(HttpSession session) - { - ResourceBundle bundle = (ResourceBundle)session.getAttribute(MESSAGE_BUNDLE); - if (bundle == null) - { - // get Locale from language selected by each user on login - Locale locale = (Locale)session.getAttribute(LOCALE); - if (locale == null) - { - bundle = ResourceBundleWrapper.getResourceBundle(MESSAGE_BUNDLE, I18NUtil.getLocale()); - } - else - { - // Only cache the bundle if/when we have a session locale - bundle = ResourceBundleWrapper.getResourceBundle(MESSAGE_BUNDLE, locale); - session.setAttribute(MESSAGE_BUNDLE, bundle); - } - } - - return bundle; - } - - /** - * Get the specified the default message bundle for this user - * - * @param context FacesContext - * - * @return ResourceBundle for this user - */ - @SuppressWarnings("unchecked") - public static ResourceBundle getBundle(FacesContext context) - { - // get the resource bundle for the current locale - // we store the bundle in the users session - // this makes it easy to add a locale per user support later - Map session = context.getExternalContext().getSessionMap(); - ResourceBundle bundle = (ResourceBundle)session.get(MESSAGE_BUNDLE); - if (bundle == null) - { - // get Locale from language selected by each user on login - Locale locale = (Locale)session.get(LOCALE); - if (locale == null) - { - bundle = ResourceBundleWrapper.getResourceBundle(MESSAGE_BUNDLE, I18NUtil.getLocale()); - } - else - { - // Only cache the bundle if/when we have a session locale - bundle = ResourceBundleWrapper.getResourceBundle(MESSAGE_BUNDLE, locale); - session.put(MESSAGE_BUNDLE, bundle); - } - } - - return bundle; - } - - /** - * Helper to get the ConfigService instance - * - * @param context FacesContext - * - * @return ConfigService - */ - public static ConfigService getConfigService(FacesContext context) - { - return (ConfigService)FacesContextUtils.getRequiredWebApplicationContext(context).getBean( - Application.BEAN_CONFIG_SERVICE); - } - - /** - * Helper to get the ConfigService instance - * - * @param context ServletContext - * - * @return ConfigService - */ - public static ConfigService getConfigService(ServletContext context) - { - return (ConfigService)WebApplicationContextUtils.getRequiredWebApplicationContext(context).getBean( - Application.BEAN_CONFIG_SERVICE); - } - - /** - * Helper to get the client config element from the config service - * - * @param context FacesContext - * @return The ClientConfigElement - */ - public static ClientConfigElement getClientConfig(FacesContext context) - { - return (ClientConfigElement)getConfigService(context).getGlobalConfig(). - getConfigElement(ClientConfigElement.CONFIG_ELEMENT_ID); - } - - /** - * Helper to get the client config element from the config service - * - * @param context ServletContext - * @return The ClientConfigElement - */ - public static ClientConfigElement getClientConfig(ServletContext context) - { - return (ClientConfigElement)getConfigService(context).getGlobalConfig(). - getConfigElement(ClientConfigElement.CONFIG_ELEMENT_ID); - } - - /** - * Returns the repository store URL - * - * @param context The spring context - * @return The repository store URL to use - */ - private static StoreRef getRepositoryStoreRef(WebApplicationContext context) - { - if (repoStoreRef == null) - { - ImporterBootstrap bootstrap = (ImporterBootstrap)context.getBean(BEAN_IMPORTER_BOOTSTRAP); - repoStoreRef = bootstrap.getStoreRef(); - } - - return repoStoreRef; - } - - /** - * Returns the root path for the application - * - * @param context The spring context - * @return The application root path - */ - private static String getRootPath(WebApplicationContext context) - { - if (rootPath == null) - { - ImporterBootstrap bootstrap = (ImporterBootstrap)context.getBean(BEAN_IMPORTER_BOOTSTRAP); - Properties configuration = bootstrap.getConfiguration(); - rootPath = configuration.getProperty("spaces.company_home.childname"); - } - - return rootPath; - } - - /** - * Returns the glossary folder name - * - * @param context The spring context - * @return The glossary folder name - */ - private static String getGlossaryFolderName(WebApplicationContext context) - { - if (glossaryFolderName == null) - { - ImporterBootstrap bootstrap = (ImporterBootstrap)context.getBean(BEAN_IMPORTER_BOOTSTRAP); - Properties configuration = bootstrap.getConfiguration(); - glossaryFolderName = configuration.getProperty("spaces.dictionary.childname"); - } - - return glossaryFolderName; - } - - /** - * Returns the Space Templates folder name - * - * @param context The spring context - * @return The templates folder name - */ - private static String getSpaceTemplatesFolderName(WebApplicationContext context) - { - if (spaceTemplatesFolderName == null) - { - ImporterBootstrap bootstrap = (ImporterBootstrap)context.getBean(BEAN_IMPORTER_BOOTSTRAP); - Properties configuration = bootstrap.getConfiguration(); - spaceTemplatesFolderName = configuration.getProperty("spaces.templates.childname"); - } - - return spaceTemplatesFolderName; - } - - /** - * Returns the Content Templates folder name - * - * @param context The spring context - * @return The templates folder name - */ - private static String getContentTemplatesFolderName(WebApplicationContext context) - { - if (contentTemplatesFolderName == null) - { - ImporterBootstrap bootstrap = (ImporterBootstrap)context.getBean(BEAN_IMPORTER_BOOTSTRAP); - Properties configuration = bootstrap.getConfiguration(); - contentTemplatesFolderName = configuration.getProperty("spaces.templates.content.childname"); - } - - return contentTemplatesFolderName; - } - - /** - * Returns the Email Templates folder name - * - * @param context The spring context - * @return The email folder name - */ - private static String getEmailTemplatesFolderName(WebApplicationContext context) - { - if (emailTemplatesFolderName == null) - { - ImporterBootstrap bootstrap = (ImporterBootstrap)context.getBean(BEAN_IMPORTER_BOOTSTRAP); - Properties configuration = bootstrap.getConfiguration(); - emailTemplatesFolderName = configuration.getProperty("spaces.templates.email.childname"); - } - - return emailTemplatesFolderName; - } - - /** - * Returns the Invite Email Templates folder name - * - * @param context The spring context - * @return The invite email folder name - */ - private static String getInviteEmailTemplatesFolderName(WebApplicationContext context) - { - if (inviteEmailTemplatesFolderName == null) - { - ImporterBootstrap bootstrap = (ImporterBootstrap) context.getBean(BEAN_IMPORTER_BOOTSTRAP); - Properties configuration = bootstrap.getConfiguration(); - inviteEmailTemplatesFolderName = configuration.getProperty("spaces.templates.email.invite1.childname"); - } - - return inviteEmailTemplatesFolderName; - } - - /** - * Returns the Notify Email Templates folder name - * - * @param context The spring context - * @return The notify email folder name - */ - private static String getNotifyEmailTemplatesFolderName(WebApplicationContext context) - { - if (notifyEmailTemplatesFolderName == null) - { - ImporterBootstrap bootstrap = (ImporterBootstrap) context.getBean(BEAN_IMPORTER_BOOTSTRAP); - Properties configuration = bootstrap.getConfiguration(); - notifyEmailTemplatesFolderName = configuration.getProperty("spaces.templates.email.notify.childname"); - } - - return notifyEmailTemplatesFolderName; - } - - /** - * Returns the RSS Templates folder name - * - * @param context The spring context - * @return The RSS folder name - */ - private static String getRSSTemplatesFolderName(WebApplicationContext context) - { - if (rssTemplatesFolderName == null) - { - ImporterBootstrap bootstrap = (ImporterBootstrap)context.getBean(BEAN_IMPORTER_BOOTSTRAP); - Properties configuration = bootstrap.getConfiguration(); - rssTemplatesFolderName = configuration.getProperty("spaces.templates.rss.childname"); - } - - return rssTemplatesFolderName; - } - - /** - * Returns the Saved Searches folder name - * - * @param context The spring context - * @return The saved searches folder name - */ - private static String getSavedSearchesFolderName(WebApplicationContext context) - { - /* - * This lookup is duplicated in a patch. If this logic changes, investigate the changes - * required for the patch(es). - */ - - if (savedSearchesFolderName == null) - { - ImporterBootstrap bootstrap = (ImporterBootstrap)context.getBean(BEAN_IMPORTER_BOOTSTRAP); - Properties configuration = bootstrap.getConfiguration(); - savedSearchesFolderName = configuration.getProperty("spaces.savedsearches.childname"); - } - - return savedSearchesFolderName; - } - - /** - * Returns the JavaScript scripts folder name - * - * @param context The spring context - * @return The scripts folder name - */ - private static String getScriptsFolderName(WebApplicationContext context) - { - if (scriptsFolderName == null) - { - ImporterBootstrap bootstrap = (ImporterBootstrap)context.getBean(BEAN_IMPORTER_BOOTSTRAP); - Properties configuration = bootstrap.getConfiguration(); - scriptsFolderName = configuration.getProperty("spaces.scripts.childname"); - } - - return scriptsFolderName; - } - - /** - * Returns the Guest Home folder name name - * - * @param context The spring context - * @return The Guest Home folder name - */ - private static String getGuestHomeFolderName(WebApplicationContext context) - { - if (guestHomeFolderName == null) - { - ImporterBootstrap bootstrap = (ImporterBootstrap)context.getBean(BEAN_IMPORTER_BOOTSTRAP); - Properties configuration = bootstrap.getConfiguration(); - guestHomeFolderName = configuration.getProperty("spaces.guest_home.childname"); - } - - return guestHomeFolderName; - } - - /** - * Retrieves the configured error page for the application - * - * @param context The Spring context - * @return The configured error page or null if the configuration is missing - */ - public static String getErrorPage(ApplicationContext context) - { - String errorPage = null; - - ConfigService svc = (ConfigService)context.getBean(BEAN_CONFIG_SERVICE); - ClientConfigElement clientConfig = (ClientConfigElement)svc.getGlobalConfig(). - getConfigElement(ClientConfigElement.CONFIG_ELEMENT_ID); - - if (clientConfig != null) - { - errorPage = clientConfig.getErrorPage(); - } - - return errorPage; - } - - /** - * Retrieves the configured login page for the application - * - * @param context The Spring contexr - * @return The configured login page or null if the configuration is missing - */ - public static String getLoginPage(ApplicationContext context) - { - String loginPage = null; - - ConfigService svc = (ConfigService)context.getBean(BEAN_CONFIG_SERVICE); - ClientConfigElement clientConfig = (ClientConfigElement)svc.getGlobalConfig(). - getConfigElement(ClientConfigElement.CONFIG_ELEMENT_ID); - - if (clientConfig != null) - { - loginPage = clientConfig.getLoginPage(); - } - - return loginPage; - } - - public static boolean isDynamicConfig(FacesContext context) - { - if (isDynamicConfig == null) - { - String dynamicConfigParam = FacesContextUtils.getRequiredWebApplicationContext(context).getServletContext().getInitParameter("org.alfresco.webclient.dynamicConfig"); - isDynamicConfig = new Boolean(((dynamicConfigParam == null) || (new Boolean(dynamicConfigParam).booleanValue() == true))); - } - - return isDynamicConfig.booleanValue(); - } -} diff --git a/war/src/main/java/org/alfresco/web/app/ContextListener.java b/war/src/main/java/org/alfresco/web/app/ContextListener.java deleted file mode 100644 index 0e6f5c5bcf..0000000000 --- a/war/src/main/java/org/alfresco/web/app/ContextListener.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; -import javax.servlet.http.HttpSessionEvent; -import javax.servlet.http.HttpSessionListener; -import javax.transaction.UserTransaction; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.repo.security.authentication.AuthenticationContext; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.repository.StoreRef; -import org.alfresco.service.cmr.search.SearchService; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.transaction.TransactionService; -import org.alfresco.web.bean.repository.Repository; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.WebApplicationContextUtils; - - -/** - * ServletContextListener implementation that initialises the application. - * - * NOTE: This class must appear after the Spring context loader listener - * - * @author gavinc - */ -public class ContextListener implements ServletContextListener, HttpSessionListener -{ - private static Log logger = LogFactory.getLog(ContextListener.class); - - private ServletContext servletContext; - - /** - * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) - */ - public void contextInitialized(ServletContextEvent event) - { - // make sure that the spaces store in the repository exists - this.servletContext = event.getServletContext(); - WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext); - - // If no context has been initialised, exit silently so config changes can be made - if (ctx == null) - { - return; - } - - ServiceRegistry registry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY); - TransactionService transactionService = registry.getTransactionService(); - NodeService nodeService = registry.getNodeService(); - SearchService searchService = registry.getSearchService(); - NamespaceService namespaceService = registry.getNamespaceService(); - AuthenticationContext authenticationContext = (AuthenticationContext) ctx - .getBean("authenticationContext"); - - // repo bootstrap code for our client - UserTransaction tx = null; - NodeRef companySpaceNodeRef = null; - try - { - tx = transactionService.getUserTransaction(); - tx.begin(); - authenticationContext.setSystemUserAsCurrentUser(); - - // get and setup the initial store ref and root path from config - StoreRef storeRef = Repository.getStoreRef(servletContext); - - // get root path - String rootPath = Application.getRootPath(servletContext); - - // Extract company space id and store it in the Application object - companySpaceNodeRef = Repository.getCompanyRoot(nodeService, searchService, namespaceService, storeRef, rootPath); - Application.setCompanyRootId(companySpaceNodeRef.getId()); - - // commit the transaction - tx.commit(); - } - catch (Throwable e) - { - // rollback the transaction - try - { - if (tx != null) - { - tx.rollback(); - } - } - catch (Exception ex) {} - - logger.error("Failed to initialise ", e); - throw new AlfrescoRuntimeException("Failed to initialise ", e); - } - finally - { - try - { - authenticationContext.clearCurrentSecurityContext(); - } - catch (Exception ex) {} - } - } - - - /** - * {@inheritDoc} - */ - public void contextDestroyed(ServletContextEvent event) - { - // NOOP - } - - /** - * Session created listener - */ - public void sessionCreated(HttpSessionEvent event) - { - if (logger.isDebugEnabled()) - logger.debug("HTTP session created: " + event.getSession().getId()); - } - - /** - * Session destroyed listener - */ - public void sessionDestroyed(HttpSessionEvent event) - { - if (logger.isDebugEnabled()) - logger.debug("HTTP session destroyed: " + event.getSession().getId()); - } -} diff --git a/war/src/main/java/org/alfresco/web/app/DebugPhaseListener.java b/war/src/main/java/org/alfresco/web/app/DebugPhaseListener.java deleted file mode 100644 index 3a1cbaa426..0000000000 --- a/war/src/main/java/org/alfresco/web/app/DebugPhaseListener.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app; - -import java.util.ArrayList; -import java.util.List; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.event.PhaseEvent; -import javax.faces.event.PhaseId; -import javax.faces.event.PhaseListener; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Debug phase listener that simply logs when each phase is entered and exited. - * - * @author gavinc - */ -public class DebugPhaseListener implements PhaseListener -{ - private static final Log logger = LogFactory.getLog(DebugPhaseListener.class); - - public int indent = 0; - public static final String INDENT = " "; - - /** - * @see javax.faces.event.PhaseListener#afterPhase(javax.faces.event.PhaseEvent) - */ - public void afterPhase(PhaseEvent event) - { - if (logger.isDebugEnabled()) - { - if (event.getPhaseId() == PhaseId.RENDER_RESPONSE) - { - printComponentTree(FacesContext.getCurrentInstance().getViewRoot()); - } - - logger.debug("********** Exiting phase: " + event.getPhaseId().toString()); - } - } - - /** - * @see javax.faces.event.PhaseListener#beforePhase(javax.faces.event.PhaseEvent) - */ - public void beforePhase(PhaseEvent event) - { - if (logger.isDebugEnabled()) - logger.debug("********** Entering phase: " + event.getPhaseId().toString()); - } - - /** - * @see javax.faces.event.PhaseListener#getPhaseId() - */ - public PhaseId getPhaseId() - { - return PhaseId.ANY_PHASE; - } - - public void printComponentTree(UIComponent comp) - { - printComponentInfo(comp); - - List complist = comp.getChildren(); - if (complist.size()>0) - indent++; - for (int i = 0; i < complist.size(); i++) - { - UIComponent uicom = (UIComponent) complist.get(i); - printComponentTree(uicom); - if (i+1 == complist.size()) - indent--; - } - } - - public void printComponentInfo(UIComponent comp) - { - if (comp.getId() == null) - { - logger.debug("UIViewRoot" + " " + "(" + comp.getClass().getName() + ")"); - } - else - { - logger.debug(getIndent() + "|"); - logger.debug(getIndent() + comp.getId() + " " + "(" + comp.getClass().getName() + ")"); - } - } - - public String getIndent() - { - String indent = ""; - for (int i=0; i. - * #L% - */ -package org.alfresco.web.app; - -import java.util.List; - -/** - * Resource bundle bootstrap bean - * - * @author Roy Wetherall - */ -public class ResourceBundleBootstrap -{ - /** - * Set the resource bundles to be registered. This should be a list of resource - * bundle base names whose content will be made available to the web client. - * - * @param resourceBundles the resource bundles - */ - public void setResourceBundles(List resourceBundles) - { - for (String resourceBundle : resourceBundles) - { - ResourceBundleWrapper.addResourceBundle(resourceBundle); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/app/ResourceBundleWrapper.java b/war/src/main/java/org/alfresco/web/app/ResourceBundleWrapper.java deleted file mode 100644 index 5c0b1d5129..0000000000 --- a/war/src/main/java/org/alfresco/web/app/ResourceBundleWrapper.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.ResourceBundle; -import java.util.Vector; - -import javax.faces.context.FacesContext; - -import org.alfresco.repo.i18n.MessageService; -import org.alfresco.service.cmr.repository.StoreRef; -import org.alfresco.web.bean.repository.Repository; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.web.jsf.FacesContextUtils; - - -/** - * Wrapper around Alfresco Resource Bundle objects. Used to catch and handle missing - * resource exception to help identify missing I18N strings in client apps. - * Also used to look for the requested string in a custom resource bundle. - * - * @author Kevin Roast - */ -public final class ResourceBundleWrapper extends ResourceBundle implements Serializable -{ - private static final long serialVersionUID = -3230653664902689948L; - private static Log logger = LogFactory.getLog(ResourceBundleWrapper.class); - - /** List of custom bundle names */ - private static List addedBundleNames = new ArrayList(10); - - /** Serializable details of the resource bundles being wrapped */ - final private Locale locale; - final private String bundleName; - - /** List of delegate resource bundles */ - transient private List delegates; - - /** Message service */ - transient private MessageService messageService; - - public static final String BEAN_RESOURCE_MESSAGE_SERVICE = "messageService"; - public static final String PATH = "app:company_home/app:dictionary/app:webclient_extension"; - - /** - * Constructor - * - * @param locale the locale - * @param bundleName the bundle name - */ - private ResourceBundleWrapper(Locale locale, String bundleName) - { - this.locale = locale; - this.bundleName = bundleName; - } - - /** - * Get the message service - * - * @return MessageService message service - */ - private MessageService getMessageService() - { - if (this.messageService == null && FacesContext.getCurrentInstance() != null) - { - this.messageService = (MessageService)FacesContextUtils.getRequiredWebApplicationContext( - FacesContext.getCurrentInstance()).getBean(BEAN_RESOURCE_MESSAGE_SERVICE); - } - return this.messageService; - } - - /** - * Get a list of the delegate resource bundles - * - * @return List list of delegate resource bundles - */ - private List getDelegates() - { - if (this.delegates == null) - { - this.delegates = new ArrayList(ResourceBundleWrapper.addedBundleNames.size() + 2); - - // Check for custom bundle (if any) - first try in the repo otherwise try the classpath - ResourceBundle customBundle = null; - - if (getMessageService() != null) - { - StoreRef storeRef = null; - String path = null; - - try - { - String customName = null; - int idx = this.bundleName.lastIndexOf("."); - if (idx != -1) - { - customName = this.bundleName.substring(idx+1, this.bundleName.length()); - } - else - { - customName = this.bundleName; - } - - storeRef = Repository.getStoreRef(); - - // TODO - make path configurable in one place ... - // Note: path here is XPath for selectNodes query - path = PATH + "/cm:" + customName; - customBundle = getMessageService().getRepoResourceBundle(Repository.getStoreRef(), path, locale); - } - catch (Throwable t) - { - // for now ... ignore the error, cannot be found or read from repo - logger.debug("Custom Web Client properties not found: " + storeRef + path); - } - } - - if (customBundle == null) - { - // also look up the custom version of the bundle in the extension package - String customName = determineCustomBundleName(this.bundleName); - customBundle = getResourceBundle(locale, customName); - } - - // Add the custom bundle (if any) - add first to allow override (eg. in MT/dynamic web client env) - if (customBundle != null) - { - this.delegates.add(customBundle); - } - - // Add the normal bundle - ResourceBundle normalBundle = getResourceBundle(locale, this.bundleName); - if (normalBundle != null) - { - this.delegates.add(normalBundle); - } - else - { - if (logger.isWarnEnabled()) - { - logger.warn("Resource bundle missing : " + this.bundleName + ", locale : " + locale); - } - } - - // Add the added bundles - for (String addedBundleName : ResourceBundleWrapper.addedBundleNames) - { - this.delegates.add(getResourceBundle(locale, addedBundleName)); - } - } - return this.delegates; - } - - /** - * Given a local and name, gets the resource bundle - * - * @param locale locale - * @param bundleName bundle name - * @return ResourceBundle resource bundle - */ - private ResourceBundle getResourceBundle(Locale locale, String bundleName) - { - ResourceBundle bundle = null; - try - { - // Load the bundle - bundle = ResourceBundle.getBundle(bundleName, locale); - this.delegates.add(bundle); - - if (logger.isDebugEnabled()) - { - logger.debug("Located and loaded bundle " + bundleName); - } - } - catch (MissingResourceException mre) - { - // ignore the error, just log some debug info - if (logger.isDebugEnabled()) - { - logger.debug("Unable to load bundle " + bundleName); - } - } - return bundle; - } - - /** - * @see java.util.ResourceBundle#getKeys() - */ - public Enumeration getKeys() - { - if (getDelegates().size() == 1) - { - return getDelegates().get(0).getKeys(); - } - else - { - Vector allKeys = new Vector(100, 2); - for (ResourceBundle delegate : getDelegates()) - { - Enumeration keys = delegate.getKeys(); - while(keys.hasMoreElements() == true) - { - allKeys.add(keys.nextElement()); - } - } - - return allKeys.elements(); - } - } - - /** - * @see java.util.ResourceBundle#handleGetObject(java.lang.String) - */ - protected Object handleGetObject(String key) - { - Object result = null; - - for (ResourceBundle delegate : getDelegates()) - { - try - { - // Try and lookup the key from the resource bundle - result = delegate.getObject(key); - if (result != null) - { - break; - } - } - catch (MissingResourceException mre) - { - // ignore as this means the key was not present - } - } - - // if the key was not found return a default string - if (result == null) - { - if (logger.isWarnEnabled() == true) - { - logger.warn("Failed to find I18N message key: " + key + " for locale: " + locale.toString()); - } - - result = "$$" + key + "$$"; - } - - return result; - } - - /** - * Factory method to get a named wrapped resource bundle for a particular locale. - * - * @param name Bundle name - * @param locale Locale to retrieve bundle for - * - * @return Wrapped ResourceBundle instance for specified locale - */ - public static ResourceBundle getResourceBundle(String name, Locale locale) - { - return new ResourceBundleWrapper(locale, name); - } - - /** - * Adds a resource bundle to the collection of custom bundles available - * - * @param name the name of the resource bundle - */ - public static void addResourceBundle(String name) - { - ResourceBundleWrapper.addedBundleNames.add(name); - } - - /** - * Determines the name for the custom bundle to lookup based on the given - * bundle name - * - * @param bundleName The standard bundle - * @return The name of the custom bundle (in the alfresco.extension package) - */ - protected static String determineCustomBundleName(String bundleName) - { - String extensionPackage = "alfresco.extension."; - String customBundleName = null; - - int idx = bundleName.lastIndexOf("."); - if (idx == -1) - { - customBundleName = extensionPackage + bundleName; - } - else - { - customBundleName = extensionPackage + - bundleName.substring(idx+1, bundleName.length()); - } - - return customBundleName; - } -} diff --git a/war/src/main/java/org/alfresco/web/app/context/IContextListener.java b/war/src/main/java/org/alfresco/web/app/context/IContextListener.java deleted file mode 100644 index 052940acc5..0000000000 --- a/war/src/main/java/org/alfresco/web/app/context/IContextListener.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.context; - -import java.io.Serializable; - -/** - * Interface used to allow Beans to register themselves as interested in UI context events. - *

- * Beans supporting this interface should be register against the UIContextService. Then Beans - * which wish to indicate that the UI should refresh itself i.e. dump all cached data and settings, - * call the UIContextService.notifyBeans() to inform all registered instances of the change. - *

- * Registered beans will also be informed of changes in location, for example when the current - * space changes or when the user has changed area i.e. from company home to my home. - * - * @author Kevin Roast - */ -public interface IContextListener extends Serializable -{ - /** - * Method called by UIContextService.notifyBeans() to inform all registered beans that - * all UI Beans should refresh dump all cached data and settings. - */ - public void contextUpdated(); - - /** - * Method called by UIContextService.spaceChanged() to inform all registered beans that - * the current space has changed. - */ - public void spaceChanged(); - - /** - * Method called by UIContextService.areaChanged() to inform all registered beans that - * the user has changed area i.e. from company home to my home. - */ - public void areaChanged(); -} diff --git a/war/src/main/java/org/alfresco/web/app/context/UIContextService.java b/war/src/main/java/org/alfresco/web/app/context/UIContextService.java deleted file mode 100644 index 5529eea775..0000000000 --- a/war/src/main/java/org/alfresco/web/app/context/UIContextService.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.context; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -import javax.faces.context.FacesContext; - -/** - * Beans supporting the IContextListener interface are registered against this class. Then Beans - * which wish to indicate that the UI should refresh itself i.e. dump all cached data and settings, - * call the UIContextService.notifyBeans() to inform all registered instances of the change. - *

- * Registered beans will also be informed of changes in location, for example when the current - * space changes or when the user has changed area i.e. from company home to my home. - * - * @author Kevin Roast - */ -public final class UIContextService implements Serializable -{ - private static final long serialVersionUID = -866750823190499704L; - - /** - * Private constructor - */ - private UIContextService() - { - } - - /** - * Returns a Session local instance of the UIContextService - * - * @return UIContextService for this Thread - */ - @SuppressWarnings("unchecked") - public static UIContextService getInstance(FacesContext fc) - { - Map session = fc.getExternalContext().getSessionMap(); - UIContextService service = (UIContextService)session.get(CONTEXT_KEY); - if (service == null) - { - service = new UIContextService(); - session.put(CONTEXT_KEY, service); - } - - return service; - } - - /** - * Register a bean to be informed of context events - * - * @param bean Conforming to the IContextListener interface - */ - public void registerBean(IContextListener bean) - { - if (bean == null) - { - throw new IllegalArgumentException("Bean reference specified cannot be null!"); - } - - this.registeredBeans.put(bean.getClass(), bean); - } - - /** - * Remove a bean reference from those notified of changes - * - * @param bean Conforming to the IContextListener interface - */ - public void unregisterBean(IContextListener bean) - { - if (bean == null) - { - throw new IllegalArgumentException("Bean reference specified cannot be null!"); - } - - this.registeredBeans.remove(bean); - } - - /** - * Returns a registered bean or null - * - * @param className (fully qualified name) - * - * @return IContextListener - */ - public IContextListener getRegisteredBean(String className) - { - IContextListener bean = null; - for (Class clazz : this.registeredBeans.keySet()) - { - if (clazz.getName().equals(className)) - { - bean = this.registeredBeans.get(clazz); - break; - } - } - return bean; - } - - /** - * Call to notify all register beans that the UI context has changed and they should - * refresh themselves as appropriate. - */ - public void notifyBeans() - { - for (IContextListener listener: this.registeredBeans.values()) - { - listener.contextUpdated(); - } - } - - /** - * Call to notify all register beans that the current space has changed and they should - * refresh themselves as appropriate. - */ - public void spaceChanged() - { - for (IContextListener listener: this.registeredBeans.values()) - { - listener.spaceChanged(); - } - } - - /** - * Call to notify all register beans that the area i.e. my home, has changed and they should - * refresh themselves as appropriate. - */ - public void areaChanged() - { - for (IContextListener listener: this.registeredBeans.values()) - { - listener.areaChanged(); - } - } - - /** key for the UI context service in the session */ - private final static String CONTEXT_KEY = "__uiContextService"; - - /** Map of bean registered against the context service */ - private Map registeredBeans = new HashMap(7, 1.0f); -} diff --git a/war/src/main/java/org/alfresco/web/app/portlet/AlfrescoDefaultViewSelector.java b/war/src/main/java/org/alfresco/web/app/portlet/AlfrescoDefaultViewSelector.java deleted file mode 100644 index 344f3722e7..0000000000 --- a/war/src/main/java/org/alfresco/web/app/portlet/AlfrescoDefaultViewSelector.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.portlet; - -import javax.portlet.PortletContext; -import javax.portlet.PortletException; -import javax.portlet.PortletSession; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; - -import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.web.app.servlet.AuthenticationHelper; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.repository.User; -import org.apache.myfaces.portlet.DefaultViewSelector; - -/** - * @author Kevin Roast - */ -public class AlfrescoDefaultViewSelector implements DefaultViewSelector -{ - /** - * Select the appropriate view ID - */ - public String selectViewId(RenderRequest request, RenderResponse response) throws PortletException - { - User user = (User) request.getPortletSession().getAttribute(AuthenticationHelper.AUTHENTICATION_USER, - PortletSession.APPLICATION_SCOPE); - if (user != null && user.getUserName().equals(AuthenticationUtil.getGuestUserName())) - { - return FacesHelper.BROWSE_VIEW_ID; - } - else - { - return null; - } - } - - /** - * @see org.apache.myfaces.portlet.DefaultViewSelector#setPortletContext(javax.portlet.PortletContext) - */ - public void setPortletContext(PortletContext portletContext) - { - } -} diff --git a/war/src/main/java/org/alfresco/web/app/portlet/AlfrescoFacesPortlet.java b/war/src/main/java/org/alfresco/web/app/portlet/AlfrescoFacesPortlet.java deleted file mode 100644 index 711cc5e70c..0000000000 --- a/war/src/main/java/org/alfresco/web/app/portlet/AlfrescoFacesPortlet.java +++ /dev/null @@ -1,748 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.portlet; - -import java.io.File; -import java.io.IOException; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.faces.application.ViewHandler; -import javax.faces.component.UIViewRoot; -import javax.faces.context.FacesContext; -import javax.portlet.ActionRequest; -import javax.portlet.ActionResponse; -import javax.portlet.MimeResponse; -import javax.portlet.PortletConfig; -import javax.portlet.PortletException; -import javax.portlet.PortletRequest; -import javax.portlet.PortletRequestDispatcher; -import javax.portlet.PortletResponse; -import javax.portlet.PortletSession; -import javax.portlet.PortletURL; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; -import javax.portlet.ResourceRequest; -import javax.portlet.ResourceResponse; -import javax.portlet.ResourceURL; -import javax.portlet.UnavailableException; -import javax.servlet.ServletRequest; - -import org.alfresco.repo.SessionUser; -import org.alfresco.repo.security.authentication.AuthenticationException; -import org.alfresco.service.cmr.security.AuthenticationService; -import org.alfresco.util.TempFileProvider; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.servlet.AuthenticationHelper; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.ErrorBean; -import org.alfresco.web.bean.FileUploadBean; -import org.alfresco.web.bean.LoginBean; -import org.alfresco.web.bean.NavigationBean; -import org.alfresco.web.bean.repository.User; -import org.alfresco.web.config.ClientConfigElement; -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; -import org.apache.commons.fileupload.portlet.PortletFileUpload; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.myfaces.portlet.MyFacesGenericPortlet; -import org.apache.myfaces.portlet.PortletUtil; -import org.springframework.context.ApplicationContext; -import org.springframework.extensions.config.ConfigService; -import org.springframework.extensions.surf.util.I18NUtil; -import org.springframework.web.context.WebApplicationContext; - -/** - * Class to extend the MyFacesGenericPortlet to provide behaviour specific to Alfresco web client. - * Handles upload of multi-part forms through a JSR-168 Portlet, generic error handling and session - * login authentication. - * - * @author Gavin Cornwell, Kevin Roast - */ -public class AlfrescoFacesPortlet extends MyFacesGenericPortlet -{ - private static final String ATTRIBUTE_LOCALE = "locale"; - private static final String PREF_ALF_USERNAME = "_alfUserName"; - private static final String SESSION_LAST_VIEW_ID = "_alfLastViewId"; - - private static final String ERROR_OCCURRED = "error-occurred"; - - private static Log logger = LogFactory.getLog(AlfrescoFacesPortlet.class); - - private String loginPage = null; - private String errorPage = null; - - - /** - * Called by the portlet container to allow the portlet to process an action request. - */ - public void processAction(ActionRequest request, ActionResponse response) - throws PortletException, IOException - { - Application.setInPortalServer(true); - try - { - // Set the current locale - I18NUtil.setLocale(getLanguage(request.getPortletSession())); - - boolean isMultipart = PortletFileUpload.isMultipartContent(request); - - // NOTE: Due to filters not being called within portlets we can not make use - // of the MyFaces file upload support, therefore we are using a pure - // portlet request/action to handle file uploads until there is a - // solution. - - if (isMultipart) - { - if (logger.isDebugEnabled()) - logger.debug("Handling multipart request..."); - - PortletSession session = request.getPortletSession(); - - // get the file from the request and put it in the session - DiskFileItemFactory factory = new DiskFileItemFactory(); - PortletFileUpload upload = new PortletFileUpload(factory); - List fileItems = upload.parseRequest(request); - Iterator iter = fileItems.iterator(); - FileUploadBean bean = new FileUploadBean(); - while(iter.hasNext()) - { - FileItem item = iter.next(); - String filename = item.getName(); - if(item.isFormField() == false) - { - if (logger.isDebugEnabled()) - logger.debug("Processing uploaded file: " + filename); - - // workaround a bug in IE where the full path is returned - // IE is only available for Windows so only check for the Windows path separator - int idx = filename.lastIndexOf('\\'); - - if (idx == -1) - { - // if there is no windows path separator check for *nix - idx = filename.lastIndexOf('/'); - } - - if (idx != -1) - { - filename = filename.substring(idx + File.separator.length()); - } - - File tempFile = TempFileProvider.createTempFile("alfresco", ".upload"); - item.write(tempFile); - bean.setFile(tempFile); - bean.setFileName(filename); - bean.setFilePath(tempFile.getAbsolutePath()); - session.setAttribute(FileUploadBean.FILE_UPLOAD_BEAN_NAME, bean, - PortletSession.PORTLET_SCOPE); - } - } - - // Set the VIEW_ID parameter to tell the faces portlet bridge to treat the request - // as a JSF request, this will send us back to the previous page we came from. - String lastViewId = (String)request.getPortletSession().getAttribute(SESSION_LAST_VIEW_ID); - if (lastViewId != null) - { - response.setRenderParameter(VIEW_ID, lastViewId); - } - } - else - { - SessionUser sessionUser = (SessionUser) request.getPortletSession().getAttribute( - AuthenticationHelper.AUTHENTICATION_USER, PortletSession.APPLICATION_SCOPE); - User user = sessionUser instanceof User ? (User) sessionUser : null; - if (user != null) - { - // setup the authentication context - try - { - WebApplicationContext ctx = (WebApplicationContext)getPortletContext().getAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); - AuthenticationService auth = (AuthenticationService)ctx.getBean("AuthenticationService"); - auth.validate(user.getTicket()); - - // save last username into portlet preferences, get from LoginBean state - LoginBean loginBean = (LoginBean)request.getPortletSession().getAttribute(AuthenticationHelper.LOGIN_BEAN); - if (loginBean != null) - { - // TODO: Need to login to the Portal to get a user here to store prefs against - // so not really a suitable solution as they get thrown away at present! - // Also would need to store prefs PER user - so auto login for each...? - String oldValue = request.getPreferences().getValue(PREF_ALF_USERNAME, null); - if (oldValue == null || oldValue.equals(loginBean.getUsernameInternal()) == false) - { - if (request.getPreferences().isReadOnly(PREF_ALF_USERNAME) == false) - { - request.getPreferences().setValue(PREF_ALF_USERNAME, loginBean.getUsernameInternal()); - request.getPreferences().store(); - } - } - } - - // do the normal JSF processing - super.processAction(request, response); - } - catch (AuthenticationException authErr) - { - // remove User object as it's now useless - request.getPortletSession().removeAttribute(AuthenticationHelper.AUTHENTICATION_USER, PortletSession.APPLICATION_SCOPE); - } - } - else - { - // do the normal JSF processing as we may be on the login page - super.processAction(request, response); - } - } - } - catch (Throwable e) - { - if (getErrorPage() != null) - { - handleError(request, response, e); - } - else - { - logger.warn("No error page configured, re-throwing exception"); - - if (e instanceof PortletException) - { - throw (PortletException)e; - } - else if (e instanceof IOException) - { - throw (IOException)e; - } - else - { - throw new PortletException(e); - } - } - } - finally - { - Application.setInPortalServer(false); - } - } - - - /* (non-Javadoc) - * @see javax.portlet.GenericPortlet#serveResource(javax.portlet.ResourceRequest, javax.portlet.ResourceResponse) - */ - @Override - public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException - { - Application.setInPortalServer(true); - try - { - super.serveResource(request, response); - } - finally - { - Application.setInPortalServer(false); - } - } - - - /** - * @see org.apache.myfaces.portlet.MyFacesGenericPortlet#facesRender(javax.portlet.RenderRequest, javax.portlet.RenderResponse) - */ - protected void facesRender(RenderRequest request, RenderResponse response) - throws PortletException, IOException - { - Application.setInPortalServer(true); - - try - { - // Set the current locale - I18NUtil.setLocale(getLanguage(request.getPortletSession())); - - if (request.getParameter(ERROR_OCCURRED) != null) - { - String errorPage = getErrorPage(); - - if (logger.isDebugEnabled()) - logger.debug("An error has occurred, redirecting to error page: " + errorPage); - - response.setContentType("text/html"); - PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(errorPage); - dispatcher.include(request, response); - } - else - { - WebApplicationContext ctx = (WebApplicationContext)getPortletContext().getAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); - AuthenticationService auth = (AuthenticationService)ctx.getBean("AuthenticationService"); - - // if we have no User object in the session then an HTTP Session timeout must have occured - // use the viewId to check that we are not already on the login page - PortletSession session = request.getPortletSession(); - String viewId = request.getParameter(VIEW_ID); - // keep track of last view id so we can use it as return page from multi-part requests - request.getPortletSession().setAttribute(SESSION_LAST_VIEW_ID, viewId); - SessionUser sessionUser = (SessionUser) request.getPortletSession().getAttribute( - AuthenticationHelper.AUTHENTICATION_USER, PortletSession.APPLICATION_SCOPE); - User user = sessionUser instanceof User ? (User)sessionUser : null; - if (user == null && (viewId == null || viewId.equals(getLoginPage()) == false)) - { - if (portalGuestAuthenticate(ctx, session, auth) != null) - { - if (logger.isDebugEnabled()) - logger.debug("Guest access successful."); - - // perform the forward to the page processed by the Faces servlet - response.setContentType("text/html"); - request.getPortletSession().setAttribute(PortletUtil.PORTLET_REQUEST_FLAG, "true"); - - // get the start location as configured by the web-client config - ConfigService configService = (ConfigService)ctx.getBean("webClientConfigService"); - ClientConfigElement configElement = (ClientConfigElement)configService.getGlobalConfig().getConfigElement("client"); - if (NavigationBean.LOCATION_MYALFRESCO.equals(configElement.getInitialLocation())) - { - nonFacesRequest(request, response, "/jsp/dashboards/container.jsp"); - } - else - { - nonFacesRequest(request, response, FacesHelper.BROWSE_VIEW_ID); - } - } - else - { - if (logger.isDebugEnabled()) - logger.debug("No valid User login, requesting login page. ViewId: " + viewId); - - // set last used username as special session value used by the LoginBean - session.setAttribute(AuthenticationHelper.SESSION_USERNAME, - request.getPreferences().getValue(PREF_ALF_USERNAME, null)); - - // login page is the default portal page - response.setContentType("text/html"); - request.getPortletSession().setAttribute(PortletUtil.PORTLET_REQUEST_FLAG, "true"); - nonFacesRequest(request, response); - } - } - else - { - if (session.getAttribute(AuthenticationHelper.SESSION_INVALIDATED) != null) - { - // remove the username preference value as explicit logout was requested by the user - if (request.getPreferences().isReadOnly(PREF_ALF_USERNAME) == false) - { - request.getPreferences().reset(PREF_ALF_USERNAME); - } - session.removeAttribute(AuthenticationHelper.SESSION_INVALIDATED); - } - - try - { - if (user != null) - { - if (logger.isDebugEnabled()) - logger.debug("Validating ticket: " + user.getTicket()); - - // setup the authentication context - auth.validate(user.getTicket()); - } - - // do the normal JSF processing - super.facesRender(request, response); - } - catch (AuthenticationException authErr) - { - // ticket is no longer valid! - if (logger.isDebugEnabled()) - logger.debug("Invalid ticket, requesting login page."); - - // remove User object as it's now useless - session.removeAttribute(AuthenticationHelper.AUTHENTICATION_USER, PortletSession.APPLICATION_SCOPE); - - // login page is the default portal page - response.setContentType("text/html"); - request.getPortletSession().setAttribute(PortletUtil.PORTLET_REQUEST_FLAG, "true"); - nonFacesRequest(request, response); - } - catch (Throwable e) - { - if (getErrorPage() != null) - { - handleError(request, response, e); - } - else - { - logger.warn("No error page configured, re-throwing exception"); - - if (e instanceof PortletException) - { - throw (PortletException)e; - } - else if (e instanceof IOException) - { - throw (IOException)e; - } - else - { - throw new PortletException(e); - } - } - } - } - } - } - finally - { - Application.setInPortalServer(false); - } - } - - /** - * Handles errors that occur during a process action request - */ - private void handleError(ActionRequest request, ActionResponse response, Throwable error) - throws PortletException, IOException - { - // get the error bean from the session and set the error that occurred. - PortletSession session = request.getPortletSession(); - ErrorBean errorBean = (ErrorBean)session.getAttribute(ErrorBean.ERROR_BEAN_NAME, - PortletSession.PORTLET_SCOPE); - if (errorBean == null) - { - errorBean = new ErrorBean(); - session.setAttribute(ErrorBean.ERROR_BEAN_NAME, errorBean, PortletSession.PORTLET_SCOPE); - } - errorBean.setLastError(error); - - response.setRenderParameter(ERROR_OCCURRED, "true"); - } - - /** - * Gets the error bean from a request - * - * @param request - * the request - * @return the error bean - */ - public static ErrorBean getErrorBean(ServletRequest request) - { - PortletRequest portletReq = (PortletRequest) request.getAttribute("javax.portlet.request"); - if (portletReq != null) - { - PortletSession session = portletReq.getPortletSession(false); - if (session != null) - { - return (ErrorBean)session.getAttribute(ErrorBean.ERROR_BEAN_NAME); - } - } - return null; - } - - /** - * Creates a render URL from the given request and parameters - * - * @param request - * the request - * @param parameters - * the parameters - * @return the render url - */ - public static String getRenderURL(ServletRequest request, Map parameters) - { - RenderResponse renderResp = (RenderResponse) request.getAttribute("javax.portlet.response"); - if (renderResp == null) - { - throw new IllegalStateException("RenderResponse object is null"); - } - - PortletURL url = renderResp.createRenderURL(); - url.setParameters(parameters); - return url.toString(); - } - - /** - * Creates an action url from the given request. - * - * @param request - * the request - * @return the action url - */ - public static String getActionURL(ServletRequest request) - { - RenderResponse renderResp = (RenderResponse) request.getAttribute("javax.portlet.response"); - if (renderResp == null) - { - throw new IllegalStateException( - "RenderResponse object is null. The web application is not executing within a portal server!"); - } - return renderResp.createActionURL().toString(); - - } - - /** - * Creates a resource URL from the given faces context. - * - * @param context - * the faces context - * @return the resource URL - */ - public static String getResourceURL(FacesContext context, String path) - { - MimeResponse portletResponse = (MimeResponse) context.getExternalContext().getResponse(); - ResourceURL resourceURL = portletResponse.createResourceURL(); - resourceURL.setResourceID(path); - return resourceURL.toString(); - } - - /** - * Gets a session attribute. - * - * @param context - * the faces context - * @param attributeName - * the attribute name - * @param shared - * get the attribute from shared (application) scope? - * @return the portlet session attribute - */ - public static Object getPortletSessionAttribute(FacesContext context, String attributeName, boolean shared) - { - Object portletReq = context.getExternalContext().getRequest(); - if (portletReq != null && portletReq instanceof PortletRequest) - { - PortletSession session = ((PortletRequest) portletReq).getPortletSession(false); - if (session != null) - { - return session.getAttribute(attributeName, shared ? PortletSession.APPLICATION_SCOPE - : PortletSession.PORTLET_SCOPE); - } - } - return null; - } - - /** - * Sets a session attribute. - * - * @param context - * the faces context - * @param attributeName - * the attribute name - * @param value - * the value - * @param shared - * set the attribute with shared (application) scope? - */ - public static void setPortletSessionAttribute(FacesContext context, String attributeName, Object value, - boolean shared) - { - Object portletReq = context.getExternalContext().getRequest(); - if (portletReq != null && portletReq instanceof PortletRequest) - { - PortletSession session = ((PortletRequest) portletReq).getPortletSession(); - session.setAttribute(attributeName, value, shared ? PortletSession.APPLICATION_SCOPE - : PortletSession.PORTLET_SCOPE); - } - else - { - context.getExternalContext().getSessionMap().put(attributeName, value); - } - } - - /** - * Initializes a new faces context using the portlet objects from a 'wrapped' servlet request. - * - * @param request - * the servlet request - * @return the faces context - */ - public static FacesContext getFacesContext(ServletRequest request) - { - PortletRequest portletReq = (PortletRequest) request.getAttribute("javax.portlet.request"); - PortletResponse portletRes = (PortletResponse) request.getAttribute("javax.portlet.response"); - PortletConfig portletConfig = (PortletConfig) request.getAttribute("javax.portlet.config"); - return FacesHelper.getFacesContext(portletReq, portletRes, portletConfig.getPortletContext()); - } - - public static String onLogOut(Object req) - { - PortletRequest portletReq = null; - if (req instanceof ServletRequest) - { - portletReq = (PortletRequest) ((ServletRequest) req).getAttribute("javax.portlet.request"); - } - else if (req instanceof PortletRequest) - { - portletReq = (PortletRequest) req; - } - - if (portletReq == null) - { - return null; - } - - // remove all objects from our session by hand - // we do this as invalidating the Portal session would invalidate all other portlets! - PortletSession session = portletReq.getPortletSession(); - SessionUser user = (SessionUser) session.getAttribute(AuthenticationHelper.AUTHENTICATION_USER, - PortletSession.APPLICATION_SCOPE); - Enumeration i = session.getAttributeNames(); - while (i.hasMoreElements()) - { - session.removeAttribute(i.nextElement()); - } - session.setAttribute(AuthenticationHelper.SESSION_INVALIDATED, true); - - return user == null ? null : user.getTicket(); - } - - /** - * Handles errors that occur during a render request - */ - private void handleError(RenderRequest request, RenderResponse response, Throwable error) - throws PortletException, IOException - { - // get the error bean from the session and set the error that occurred. - PortletSession session = request.getPortletSession(); - ErrorBean errorBean = (ErrorBean)session.getAttribute(ErrorBean.ERROR_BEAN_NAME, - PortletSession.PORTLET_SCOPE); - if (errorBean == null) - { - errorBean = new ErrorBean(); - session.setAttribute(ErrorBean.ERROR_BEAN_NAME, errorBean, PortletSession.PORTLET_SCOPE); - } - errorBean.setLastError(error); - - // if the faces context is available set the current view to the browse page - // so that the error page goes back to the application (rather than going back - // to the same page which just throws the error again meaning we can never leave - // the error page) - FacesContext context = FacesContext.getCurrentInstance(); - if (context != null) - { - ViewHandler viewHandler = context.getApplication().getViewHandler(); - // TODO: configure the portlet error return page - UIViewRoot view = viewHandler.createView(context, FacesHelper.BROWSE_VIEW_ID); - context.setViewRoot(view); - } - - // get the error page and include that instead - String errorPage = getErrorPage(); - - if (logger.isDebugEnabled()) - logger.debug("An error has occurred, redirecting to error page: " + errorPage); - - response.setContentType("text/html"); - PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(errorPage); - dispatcher.include(request, response); - } - - /** - * @see org.apache.myfaces.portlet.MyFacesGenericPortlet#setDefaultViewSelector() - */ - protected void setDefaultViewSelector() throws UnavailableException - { - super.setDefaultViewSelector(); - if (this.defaultViewSelector == null) - { - this.defaultViewSelector = new AlfrescoDefaultViewSelector(); - } - } - - /** - * For no previous authentication or forced Guest - attempt Guest access - * - * @param ctx WebApplicationContext - * @param auth AuthenticationService - */ - private static User portalGuestAuthenticate(WebApplicationContext ctx, PortletSession session, AuthenticationService auth) - { - User user = AuthenticationHelper.portalGuestAuthenticate(ctx, auth); - - if (user != null) - { - // store the User object in the Session - the authentication servlet will then proceed - session.setAttribute(AuthenticationHelper.AUTHENTICATION_USER, user, PortletSession.APPLICATION_SCOPE); - - // Set the current locale - I18NUtil.setLocale(getLanguage(session)); - - // remove the session invalidated flag - session.removeAttribute(AuthenticationHelper.SESSION_INVALIDATED); - } - return user; - } - - /** - * Return the language Locale for the current user Session. - * - * @param session PortletSession for the current user - * - * @return Current language Locale set or the VM default if none set - never null - */ - private static Locale getLanguage(PortletSession session) - { - Locale locale = (Locale)session.getAttribute(ATTRIBUTE_LOCALE); - if (locale == null) - { - locale = Application.getLanguage((ApplicationContext)session.getPortletContext().getAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)); - - // save in user session - session.setAttribute(ATTRIBUTE_LOCALE, locale); - } - return locale; - } - - /** - * @return Retrieves the configured login page - */ - private String getLoginPage() - { - if (this.loginPage == null) - { - this.loginPage = Application.getLoginPage((ApplicationContext)getPortletContext().getAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)); - } - - return this.loginPage; - } - - /** - * @return Retrieves the configured error page - */ - private String getErrorPage() - { - if (this.errorPage == null) - { - this.errorPage = Application.getErrorPage((ApplicationContext)getPortletContext().getAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)); - } - - return this.errorPage; - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/AbstractAuthenticationFilter.java b/war/src/main/java/org/alfresco/web/app/servlet/AbstractAuthenticationFilter.java deleted file mode 100644 index a00b87a509..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/AbstractAuthenticationFilter.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.StringTokenizer; - -import javax.servlet.Filter; -import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - - -/** - * Base class for all externally based authentication mechanism filters - */ -public abstract class AbstractAuthenticationFilter implements Filter -{ - private static Log logger = LogFactory.getLog(AbstractAuthenticationFilter.class); - - /** Request level marker to indicate that authentication should not be processed */ - final static String NO_AUTH_REQUIRED = "alfNoAuthRequired"; - - - /** - * Parse the Accept-Lanaguage HTTP header value - * - * @param req HttpServletRequest - * @return Locale - */ - public static final Locale parseAcceptLanguageHeader(HttpServletRequest req, List m_languages) - { - // Default the locale - - Locale locale = Locale.getDefault(); - - // Get the accept language header value - - String acceptHeader = req.getHeader("Accept-Language"); - if ( acceptHeader != null) - { - // Parse the accepted language list - - StringTokenizer tokens = new StringTokenizer(acceptHeader, ","); - List langList = new ArrayList(); - - while ( tokens.hasMoreTokens()) - { - // Get the current language token - - String lang = tokens.nextToken(); - float quality = 1.0f; - - // Check if the optional quality has been specified - - int qpos = lang.indexOf(";"); - if ( qpos != -1) - { - // Parse the quality value - - try - { - quality = Float.parseFloat(lang.substring(qpos+3)); - } - catch (NumberFormatException ex) - { - logger.error("Error parsing Accept-Language value " + lang); - } - - // Strip the quality value from the language token - - lang = lang.substring(0,qpos); - } - - // Add the language to the list - - langList.add(new AcceptLanguage(lang, quality)); - } - - // Debug - - if ( logger.isDebugEnabled()) - logger.debug("Accept-Language list : " + langList); - - // Match the client languages to the available locales - - if ( langList.size() > 0) - { - // Search for the best match locale to use for this client - - AcceptLanguage useLang = null; - String useName = null; - boolean match = false; - - for ( AcceptLanguage curLang : langList) - { - // Match against the available languages - - for(String availLang : m_languages) - { - // The accept language may be in 'cc' or 'cc_cc' format - - match = false; - - if ( curLang.getLanguage().length() == 2) - { - if ( availLang.startsWith(curLang.getLanguage())) - match = true; - } - else if ( availLang.equalsIgnoreCase(curLang.getLanguage())) - match = true; - - // If we found a match check if it is a higher quality than the current match. - // If the quality is the same we stick with the existing match as it was nearer the - // start of the list. - - if ( match == true) - { - if ( useLang == null || - ( curLang.getQuality() > useLang.getQuality())) - { - useLang = curLang; - useName = availLang; - } - } - } - } - - // Debug - - if ( logger.isDebugEnabled()) - logger.debug("Accept-Language using " + (useLang != null ? useLang.toString() : "")); - - // Create the required user locale - - if ( useLang != null) - { - Locale useLocale = AcceptLanguage.createLocale(useName); - if ( useLocale != null) - { - locale = useLocale; - - // Debug - - if ( logger.isDebugEnabled()) - logger.debug("Using language " + useLang + ", locale " + locale); - } - } - } - } - - // Return the selected locale - - return locale; - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/AcceptLanguage.java b/war/src/main/java/org/alfresco/web/app/servlet/AcceptLanguage.java deleted file mode 100644 index dd3e321a19..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/AcceptLanguage.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ - -package org.alfresco.web.app.servlet; - -import java.util.Locale; -import java.util.StringTokenizer; - -/** - * Accept Language Class - * - *

Holds the details of an accepted language from a HTTP Accept-Language header - * - * @author gkspencer - */ -class AcceptLanguage -{ - // Language name - - private String m_language; - - // Quality - - private float m_quality = 1.0f; - - /** - * Class constructor - * - * @param lang String - * @param quality float - */ - public AcceptLanguage(String lang, float quality) - { - // Convert the language to Java format - - m_language = lang.replace('-', '_'); - m_quality = quality; - } - - /** - * Return the language - * - * @return String - */ - public final String getLanguage() - { - return m_language; - } - - /** - * Return the quality - * - * @return float - */ - public final float getQuality() - { - return m_quality; - } - - /** - * Create a locale for this language - * - * @return Locale - */ - public final Locale createLocale() - { - return createLocale(getLanguage()); - } - - /** - * Create a locale for this language - * - * @param locName String - * @return Locale - */ - public final static Locale createLocale(String locName) - { - Locale locale = null; - - StringTokenizer t = new StringTokenizer(locName, "_"); - int tokens = t.countTokens(); - if (tokens == 1) - { - locale = new Locale(locName); - } - else if (tokens == 2) - { - locale = new Locale(t.nextToken(), t.nextToken()); - } - else if (tokens == 3) - { - locale = new Locale(t.nextToken(), t.nextToken(), t.nextToken()); - } - - return locale; - } - - /** - * Return the accept language as a string - * - * @return String - */ - public String toString() - { - StringBuilder str = new StringBuilder(); - - str.append("["); - str.append(getLanguage()); - str.append(","); - str.append(getQuality()); - str.append("]"); - - return str.toString(); - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/AdminAuthenticationFilter.java b/war/src/main/java/org/alfresco/web/app/servlet/AdminAuthenticationFilter.java deleted file mode 100644 index 2bbf4a535d..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/AdminAuthenticationFilter.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.web.bean.repository.User; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * This servlet filter is used to restrict direct URL access to administration - * resource in the web client, for example the admin console. - * - * @author gavinc - * @deprecated 5.0 not exposed in web-client web.xml - */ -public class AdminAuthenticationFilter implements Filter -{ - private static final Log logger = LogFactory.getLog(AdminAuthenticationFilter.class); - - private FilterConfig config; - - /** - * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) - */ - public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) - throws IOException, ServletException - { - HttpServletRequest httpRequest = (HttpServletRequest)req; - HttpServletResponse httpResponse = (HttpServletResponse)res; - - // The fact that this filter is being called means a request for a protected - // resource has taken place, check that the current user is in fact an - // administrator. - - if (logger.isDebugEnabled()) - logger.debug("Authorising request for protected resource: " + httpRequest.getRequestURI()); - - // there should be a user at this point so retrieve it - User user = AuthenticationHelper.getUser(this.config.getServletContext(), httpRequest, httpResponse); - - // if the user is present check to see whether it is an admin user - boolean isAdmin = (user != null && user.isAdmin()); - - if (isAdmin) - { - if (logger.isDebugEnabled()) - logger.debug("Current user has admin authority, allowing access."); - - // continue filter chaining if current user is admin user - chain.doFilter(req, res); - } - else - { - // return the 401 Forbidden error as the current user is not an administrator - // if the response has already been committed there's nothing we can do but - // print out a warning - if (httpResponse.isCommitted() == false) - { - if (logger.isDebugEnabled()) - logger.debug("Current user does not have admin authority, returning 401 Forbidden error..."); - - httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN); - } - else - { - if (logger.isWarnEnabled()) - logger.warn("Access denied to '" + httpRequest.getRequestURI() + - "'. The response has already been committed so a 401 Forbidden error could not be sent!"); - } - } - } - - /** - * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) - */ - public void init(FilterConfig config) throws ServletException - { - this.config = config; - } - - /** - * @see javax.servlet.Filter#destroy() - */ - public void destroy() - { - // nothing to do - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/AlfrescoX509ServletFilter.java b/war/src/main/java/org/alfresco/web/app/servlet/AlfrescoX509ServletFilter.java deleted file mode 100644 index 921bb4e36b..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/AlfrescoX509ServletFilter.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ - -package org.alfresco.web.app.servlet; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.WebApplicationContextUtils; -import org.alfresco.web.scripts.servlet.X509ServletFilterBase; - -import javax.servlet.*; -import java.io.IOException; -import java.util.Properties; - -/** - * The AlfrescoX509ServletFilter implements the checkEnforce method of the X509ServletFilterBase. - * This allows the configuration of X509 authentication to be toggled on/off through a - * configuration outside of the web.xml. - **/ - -public class AlfrescoX509ServletFilter extends X509ServletFilterBase -{ - private static final String BEAN_GLOBAL_PROPERTIES = "global-properties"; - private static final String SECURE_COMMS = "solr.secureComms"; - - private static Log logger = LogFactory.getLog(AlfrescoX509ServletFilter.class); - - @Override - protected boolean checkEnforce(ServletContext servletContext) throws IOException - { - /* - * Get the secureComms setting from the global properties bean. - */ - - WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); - Properties globalProperties = (Properties) wc.getBean(BEAN_GLOBAL_PROPERTIES); - String prop = globalProperties.getProperty(SECURE_COMMS); - - if(logger.isDebugEnabled()) - { - logger.debug("secureComms:"+prop); - } - - /* - * Return true or false based on the property. This will switch on/off X509 enforcement in the X509ServletFilterBase. - */ - - if (prop == null || "none".equals(prop)) - { - return false; - } - else - { - return true; - } - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/app/servlet/AuthenticationFilter.java b/war/src/main/java/org/alfresco/web/app/servlet/AuthenticationFilter.java deleted file mode 100644 index df49c3a154..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/AuthenticationFilter.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; - -import javax.servlet.FilterChain; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.extensions.config.ConfigService; -import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.repo.web.filter.beans.DependencyInjectedFilter; -import org.springframework.extensions.surf.util.AbstractLifecycleBean; -import org.alfresco.web.config.ClientConfigElement; -import org.springframework.context.ApplicationEvent; - -/** - * @author Kevin Roast - * - * Servlet filter responsible for redirecting to the login page for the Web Client if the user - * does not have a valid ticket. - *

- * The current ticket is validated for each page request and the login page is shown if the - * ticket has expired. - *

- * Note that this filter is only active when the system is running in a servlet container - - * the AlfrescoFacesPortlet will be used for a JSR-168 Portal environment. - * - * @deprecated 5.0 not exposed in web-client web.xml - */ -public class AuthenticationFilter extends AbstractLifecycleBean implements DependencyInjectedFilter -{ - private String loginPage; - private ConfigService configService; - - /** - * @param configService - * the configService to set - */ - public void setConfigService(ConfigService configService) - { - this.configService = configService; - } - - /* (non-Javadoc) - * @see org.springframework.extensions.surf.util.AbstractLifecycleBean#onBootstrap(org.springframework.context.ApplicationEvent) - */ - @Override - protected void onBootstrap(ApplicationEvent event) - { - if (this.loginPage == null) - { - ClientConfigElement clientConfig = (ClientConfigElement) this.configService.getGlobalConfig() - .getConfigElement(ClientConfigElement.CONFIG_ELEMENT_ID); - - if (clientConfig != null) - { - this.loginPage = clientConfig.getLoginPage(); - } - } - } - - /* (non-Javadoc) - * @see org.springframework.extensions.surf.util.AbstractLifecycleBean#onShutdown(org.springframework.context.ApplicationEvent) - */ - @Override - protected void onShutdown(ApplicationEvent event) - { - } - - public void doFilter(ServletContext context, ServletRequest req, ServletResponse res, FilterChain chain) - throws IOException, ServletException - { - HttpServletRequest httpReq = (HttpServletRequest) req; - HttpServletResponse httpRes = (HttpServletResponse) res; - - // allow the login page to proceed - if (!httpReq.getRequestURI().endsWith(this.loginPage)) - { - AuthenticationStatus status = AuthenticationHelper.authenticate(context, httpReq, httpRes, false); - - if (status == AuthenticationStatus.Success || status == AuthenticationStatus.Guest) - { - // continue filter chaining - chain.doFilter(req, res); - } - else - { - // authentication failed - so end servlet execution and redirect to login page - // also save the requested URL so the login page knows where to redirect too later - BaseServlet.redirectToLoginPage(httpReq, httpRes, context); - } - } - else - { - // continue filter chaining - chain.doFilter(req, res); - AuthenticationUtil.clearCurrentSecurityContext(); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/AuthenticationHelper.java b/war/src/main/java/org/alfresco/web/app/servlet/AuthenticationHelper.java deleted file mode 100644 index 95723c2170..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/AuthenticationHelper.java +++ /dev/null @@ -1,777 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; - -import javax.faces.context.FacesContext; -import javax.servlet.ServletContext; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.SessionUser; -import org.alfresco.repo.management.subsystems.ActivateableBean; -import org.alfresco.repo.security.authentication.AuthenticationComponent; -import org.alfresco.repo.security.authentication.AuthenticationException; -import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.repo.security.authentication.external.RemoteUserMapper; -import org.alfresco.repo.security.permissions.AccessDeniedException; -import org.alfresco.repo.transaction.RetryingTransactionHelper; -import org.alfresco.repo.webdav.auth.AuthenticationDriver; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.security.AuthenticationService; -import org.alfresco.service.cmr.security.AuthorityService; -import org.alfresco.service.cmr.security.PersonService; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.portlet.AlfrescoFacesPortlet; -import org.alfresco.web.bean.LoginBean; -import org.alfresco.web.bean.repository.User; -import org.alfresco.web.bean.users.UserPreferencesBean; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.extensions.surf.util.Base64; -import org.springframework.extensions.surf.util.I18NUtil; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.WebApplicationContextUtils; - -/** - * Helper to authenticate the current user using available Ticket information. - *

- * User information is looked up in the Session. If found the ticket is retrieved and validated. - * If the ticket is invalid then a redirect is performed to the login page. - *

- * If no User info is found then a search will be made for a previous username stored in a Cookie - * value. If the username if found then a redirect to the Login page will occur. If no username - * is found then Guest access login will be attempted by the system. Guest access can be forced - * with the appropriate method call. - * - * @author Kevin Roast - */ -public final class AuthenticationHelper -{ - /** session variables */ - public static final String AUTHENTICATION_USER = AuthenticationDriver.AUTHENTICATION_USER; - public static final String SESSION_USERNAME = "_alfLastUser"; - public static final String SESSION_INVALIDATED = "_alfSessionInvalid"; - - /** JSF bean IDs */ - public static final String LOGIN_BEAN = "LoginBean"; - - /** public service bean IDs **/ - private static final String AUTHENTICATION_SERVICE = "AuthenticationService"; - private static final String AUTHENTICATION_COMPONENT = "AuthenticationComponent"; - private static final String REMOTE_USER_MAPPER = "RemoteUserMapper"; - private static final String UNPROTECTED_AUTH_SERVICE = "authenticationService"; - private static final String PERSON_SERVICE = "personService"; - private static final String AUTHORITY_SERVICE = "AuthorityService"; - - /** cookie names */ - private static final String COOKIE_ALFUSER = "alfUser0"; - - private static Log logger = LogFactory.getLog(AuthenticationHelper.class); - - - /** - * Does all the stuff you need to do after successfully authenticating/validating a user ticket to set up the request - * thread. A useful utility method for an authentication filter. - * - * @param sc - * the servlet context - * @param req - * the request - * @param res - * the response - */ - public static void setupThread(ServletContext sc, HttpServletRequest req, HttpServletResponse res, boolean useInterfaceLanguage) - { - if (logger.isDebugEnabled()) - logger.debug("Setting up the request thread."); - // setup faces context - FacesContext fc = Application.inPortalServer() ? AlfrescoFacesPortlet.getFacesContext(req) : FacesHelper.getFacesContext(req, res, sc); - - // Set the current locale and language (overriding the one already decoded from the Accept-Language header - if (WebApplicationContextUtils.getRequiredWebApplicationContext(sc).containsBean(Application.BEAN_CONFIG_SERVICE)) - { - I18NUtil.setLocale(Application.getLanguage(req.getSession(), Application.getClientConfig(fc).isLanguageSelect() && useInterfaceLanguage)); - } - else - { - Application.getLanguage(req.getSession(), false); - } - if (logger.isDebugEnabled()) - logger.debug("The general locale is : " + I18NUtil.getLocale()); - - // Programatically retrieve the UserPreferencesBean from JSF - UserPreferencesBean userPreferencesBean = (UserPreferencesBean) FacesHelper.getManagedBean(fc, "UserPreferencesBean"); - if (logger.isDebugEnabled()) - logger.debug("The UserPreferencesBean is : " + userPreferencesBean); - if (userPreferencesBean != null) - { - String contentFilterLanguageStr = userPreferencesBean.getContentFilterLanguage(); - if (contentFilterLanguageStr != null) - { - // Set the locale for the method interceptor for MLText properties - I18NUtil.setContentLocale(I18NUtil.parseLocale(contentFilterLanguageStr)); - } - else - { - // Nothing has been selected, so remove the content filter - I18NUtil.setContentLocale(null); - } - if (logger.isDebugEnabled()) - logger.debug("The content locale is : " + I18NUtil.getContentLocale()); - } - } - - /** - * Helper to authenticate the current user using session based Ticket information. - *

- * User information is looked up in the Session. If found the ticket is retrieved and validated. - * If no User info is found or the ticket is invalid then a redirect is performed to the login page. - * - * @param forceGuest True to force a Guest login attempt - * - * @return AuthenticationStatus result. - */ - public static AuthenticationStatus authenticate( - ServletContext sc, HttpServletRequest req, HttpServletResponse res, boolean forceGuest) - throws IOException - { - return authenticate(sc, req, res, forceGuest, true); - } - - /** - * Helper to authenticate the current user using session based Ticket information. - *

- * User information is looked up in the Session. If found the ticket is retrieved and validated. - * If no User info is found or the ticket is invalid then a redirect is performed to the login page. - * - * @param forceGuest True to force a Guest login attempt - * @param allowGuest True to allow the Guest user if no user object represent - * - * @return AuthenticationStatus result. - */ - public static AuthenticationStatus authenticate( - ServletContext sc, HttpServletRequest req, HttpServletResponse res, boolean forceGuest, boolean allowGuest) - throws IOException - { - if (logger.isDebugEnabled()) - logger.debug("Authenticating the current user using session based Ticket information."); - // retrieve the User object - User user = getUser(sc, req, res); - - HttpSession session = req.getSession(); - - // get the login bean if we're not in the portal - LoginBean loginBean = null; - if (Application.inPortalServer() == false) - { - if (logger.isDebugEnabled()) - logger.debug("We're not in the portal, getting the login bean."); - loginBean = (LoginBean)session.getAttribute(LOGIN_BEAN); - } - - // setup the authentication context - WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(sc); - AuthenticationService auth = (AuthenticationService)wc.getBean(AUTHENTICATION_SERVICE); - - if (logger.isDebugEnabled()) - logger.debug("Force guest is: " + forceGuest); - if (user == null || forceGuest) - { - if (logger.isDebugEnabled()) - logger.debug("The user is null."); - // Check for the session invalidated flag - this is set by the Logout action in the LoginBean - // it signals a forced Logout and means we should not immediately attempt a relogin as Guest. - // The attribute is removed from the session by the login.jsp page after the Cookie containing - // the last stored username string is cleared. - if (session.getAttribute(AuthenticationHelper.SESSION_INVALIDATED) == null) - { - if (logger.isDebugEnabled()) - logger.debug("The session is not invalidated."); - Cookie authCookie = getAuthCookie(req); - if (allowGuest == true && (authCookie == null || forceGuest)) - { - if (logger.isDebugEnabled()) - logger.debug("No previous authentication or forced Guest - attempt Guest access."); - try - { - auth.authenticateAsGuest(); - - // if we get here then Guest access was allowed and successful - setUser(sc, req, AuthenticationUtil.getGuestUserName(), auth.getCurrentTicket(), false); - - // Set up the thread context - setupThread(sc, req, res, true); - - // remove the session invalidated flag - session.removeAttribute(AuthenticationHelper.SESSION_INVALIDATED); - - if (logger.isDebugEnabled()) - logger.debug("Successfully authenticated as guest."); - // it is the responsibilty of the caller to handle the Guest return status - return AuthenticationStatus.Guest; - } - catch (AuthenticationException guestError) - { - if (logger.isDebugEnabled()) - logger.debug("An AuthenticationException occurred, expected if Guest access not allowed - continue to login page as usual", guestError); - } - catch (AccessDeniedException accessError) - { - // Guest is unable to access either properties on Person - AuthenticationService unprotAuthService = (AuthenticationService)wc.getBean(UNPROTECTED_AUTH_SERVICE); - unprotAuthService.invalidateTicket(unprotAuthService.getCurrentTicket()); - unprotAuthService.clearCurrentSecurityContext(); - logger.warn("Unable to login as Guest: ", accessError); - } - catch (Throwable e) - { - // Some other kind of serious failure to report - AuthenticationService unprotAuthService = (AuthenticationService)wc.getBean(UNPROTECTED_AUTH_SERVICE); - unprotAuthService.invalidateTicket(unprotAuthService.getCurrentTicket()); - unprotAuthService.clearCurrentSecurityContext(); - throw new AlfrescoRuntimeException("Failed to authenticate as Guest user.", e); - } - } - } - if (logger.isDebugEnabled()) - logger.debug("Session invalidated - return to login screen."); - return AuthenticationStatus.Failure; - } - else - { - if (logger.isDebugEnabled()) - logger.debug("The user is: " + user.getUserName()); - // set last authentication username cookie value - String loginName; - if (loginBean != null && (loginName = loginBean.getUsernameInternal()) != null) - { - if (logger.isDebugEnabled()) - logger.debug("Set last authentication username cookie value"); - setUsernameCookie(req, res, loginName); - } - - // Set up the thread context - setupThread(sc, req, res, true); - - return AuthenticationStatus.Success; - } - } - - /** - * Helper to authenticate the current user using the supplied Ticket value. - * - * @return true if authentication successful, false otherwise. - */ - public static AuthenticationStatus authenticate( - ServletContext context, HttpServletRequest httpRequest, HttpServletResponse httpResponse, String ticket) - throws IOException - { - if (logger.isDebugEnabled()) - logger.debug("Authenticate the current user using the supplied Ticket value."); - // setup the authentication context - WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(context); - AuthenticationService auth = (AuthenticationService)wc.getBean(AUTHENTICATION_SERVICE); - HttpSession session = httpRequest.getSession(); - try - { - // If we already have a cached user, make sure it is for the right ticket - SessionUser user = (SessionUser)session.getAttribute(AuthenticationHelper.AUTHENTICATION_USER); - if (user != null && !user.getTicket().equals(ticket)) - { - if (logger.isDebugEnabled()) - logger.debug("Found a previously-cached user with the wrong identity."); - session.removeAttribute(AUTHENTICATION_USER); - if (!Application.inPortalServer()) - { - if (logger.isDebugEnabled()) - logger.debug("The server is not running in a portal, invalidating session."); - session.invalidate(); - session = httpRequest.getSession(); - } - user = null; - } - - // Validate the ticket and associate it with the session - auth.validate(ticket); - - if (user == null) - { - if (logger.isDebugEnabled()) - logger.debug("Ticket is valid; caching a new user in the session."); - setUser(context, httpRequest, auth.getCurrentUserName(), ticket, false); - } - else if (logger.isDebugEnabled()) - logger.debug("Ticket is valid; retaining cached user in session."); - } - catch (AuthenticationException authErr) - { - if (logger.isDebugEnabled()) - logger.debug("An AuthenticationException occured: ", authErr); - session.removeAttribute(AUTHENTICATION_USER); - if (!Application.inPortalServer()) - { - if (logger.isDebugEnabled()) - logger.debug("The server is not running in a portal, invalidating session."); - session.invalidate(); - } - return AuthenticationStatus.Failure; - } - catch (Throwable e) - { - if (logger.isDebugEnabled()) - logger.debug("Authentication failed due to unexpected error", e); - // Some other kind of serious failure - AuthenticationService unprotAuthService = (AuthenticationService)wc.getBean(UNPROTECTED_AUTH_SERVICE); - unprotAuthService.invalidateTicket(unprotAuthService.getCurrentTicket()); - unprotAuthService.clearCurrentSecurityContext(); - return AuthenticationStatus.Failure; - } - - // As we are authenticating via a ticket, establish the session locale using request headers rather than web client preferences - setupThread(context, httpRequest, httpResponse, false); - - return AuthenticationStatus.Success; - } - - /** - * Creates an object for an authenticated user and stores it in the session. - * - * @param context - * the servlet context - * @param req - * the request - * @param currentUsername - * the current user name - * @param ticket - * a validated ticket - * @param externalAuth - * was this user authenticated externally? - * @return the user object - */ - public static User setUser(ServletContext context, HttpServletRequest req, String currentUsername, - String ticket, boolean externalAuth) - { - if (logger.isDebugEnabled()) - logger.debug("Creating an object for " + currentUsername + " and storing it in the session"); - WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(context); - - User user = createUser(wc, currentUsername, ticket); - // store the User object in the Session - the authentication servlet will then proceed - HttpSession session = req.getSession(true); - session.setAttribute(AuthenticationHelper.AUTHENTICATION_USER, user); - setExternalAuth(session, externalAuth); - return user; - } - - /** - * Sets or clears the external authentication flag on the session - * - * @param session - * the session - * @param externalAuth - * was the user authenticated externally? - */ - private static void setExternalAuth(HttpSession session, boolean externalAuth) - { - if (logger.isDebugEnabled()) - logger.debug("Settings the external authentication flag on the session to " + externalAuth); - if (externalAuth) - { - session.setAttribute(LoginBean.LOGIN_EXTERNAL_AUTH, Boolean.TRUE); - } - else - { - session.removeAttribute(LoginBean.LOGIN_EXTERNAL_AUTH); - } - } - - /** - * Creates an object for an authentication user. - * - * @param wc - * the web application context - * @param currentUsername - * the current user name - * @param ticket - * a validated ticket - * @return the user object - */ - private static User createUser(final WebApplicationContext wc, final String currentUsername, final String ticket) - { - if (logger.isDebugEnabled()) - logger.debug("Creating an object for " + currentUsername + " with ticket: " + ticket); - final ServiceRegistry services = (ServiceRegistry) wc.getBean(ServiceRegistry.SERVICE_REGISTRY); - - // If the repository is read only, we have to settle for a read only transaction. Auto user creation - // will not be possible. - boolean readOnly = services.getTransactionService().isReadOnly(); - - return services.getTransactionService().getRetryingTransactionHelper().doInTransaction( - new RetryingTransactionHelper.RetryingTransactionCallback() - { - public User execute() throws Throwable - { - NodeService nodeService = services.getNodeService(); - PersonService personService = (PersonService) wc.getBean(PERSON_SERVICE); - NodeRef personRef = personService.getPerson(currentUsername); - User user = new User(currentUsername, ticket, personRef); - NodeRef homeRef = (NodeRef) nodeService.getProperty(personRef, ContentModel.PROP_HOMEFOLDER); - - if (homeRef==null || !nodeService.exists(homeRef)) - { - throw new AuthenticationException("Home folder is missing for user " + currentUsername); - } - - user.setHomeSpaceId(homeRef.getId()); - return user; - } - }, readOnly, false); - } - - /** - * For no previous authentication or forced Guest - attempt Guest access - * - * @param ctx - * WebApplicationContext - * @param auth - * AuthenticationService - */ - public static User portalGuestAuthenticate(WebApplicationContext ctx, AuthenticationService auth) - { - if (logger.isDebugEnabled()) - logger.debug("Authenticating the current user as Guest in a portal."); - try - { - auth.authenticateAsGuest(); - - return createUser(ctx, AuthenticationUtil.getGuestUserName(), auth.getCurrentTicket()); - } - catch (AuthenticationException guestError) - { - if (logger.isDebugEnabled()) - logger.debug("An AuthenticationException occurred, expected if Guest access not allowed - continue to login page as usual", guestError); - } - catch (AccessDeniedException accessError) - { - // Guest is unable to access either properties on Person - AuthenticationService unprotAuthService = (AuthenticationService) ctx.getBean(UNPROTECTED_AUTH_SERVICE); - unprotAuthService.invalidateTicket(unprotAuthService.getCurrentTicket()); - unprotAuthService.clearCurrentSecurityContext(); - logger.warn("Unable to login as Guest: " + accessError.getMessage()); - } - catch (Throwable e) - { - if (logger.isDebugEnabled()) - logger.debug("Unexpected error authenticating as Guest in a portal.", e); - // Some other kind of serious failure to report - AuthenticationService unprotAuthService = (AuthenticationService) ctx.getBean(UNPROTECTED_AUTH_SERVICE); - unprotAuthService.invalidateTicket(unprotAuthService.getCurrentTicket()); - unprotAuthService.clearCurrentSecurityContext(); - throw new AlfrescoRuntimeException("Failed to authenticate as Guest user.", e); - } - return null; - } - - /** - * Uses the remote user mapper, if one is configured, to extract a user ID from the request - * - * @param sc - * the servlet context - * @param httpRequest - * The HTTP request - * @return the user ID if a user has been externally authenticated or null otherwise. - */ - public static String getRemoteUser(final ServletContext sc, final HttpServletRequest httpRequest) - { - String userId = null; - - // If the remote user mapper is configured, we may be able to map in an externally authenticated user - RemoteUserMapper remoteUserMapper = getRemoteUserMapper(sc); - if (remoteUserMapper != null) - { - userId = remoteUserMapper.getRemoteUser(httpRequest); - } - if (logger.isDebugEnabled()) - { - if (userId == null) - { - logger.debug("No external user ID in request."); - } - else - { - logger.debug("Extracted external user ID from request: " + userId); - } - } - - return userId; - } - - /** - * Gets the remote user mapper if one is configured and active (i.e. external authentication is in use). - * @param sc - * the servlet context - * @return the remote user mapper if one is configured and active; otherwise null - */ - public static RemoteUserMapper getRemoteUserMapper(final ServletContext sc) - { - final WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(sc); - RemoteUserMapper remoteUserMapper = (RemoteUserMapper) wc.getBean(REMOTE_USER_MAPPER); - if (remoteUserMapper != null && !(remoteUserMapper instanceof ActivateableBean) || ((ActivateableBean) remoteUserMapper).isActive()) - { - if (logger.isDebugEnabled()) - { - logger.debug("Remote user mapper configured and active."); - } - return remoteUserMapper; - } - if (logger.isDebugEnabled()) - { - logger.debug("No active remote user mapper."); - } - return null; - } - - /** - * Attempts to retrieve the User object stored in the current session. - * - * @param sc - * the servlet context - * @param httpRequest - * The HTTP request - * @param httpResponse - * The HTTP response - * @return The User object representing the current user or null if it could not be found - */ - public static User getUser(final ServletContext sc, final HttpServletRequest httpRequest, HttpServletResponse httpResponse) - { - // If the remote user mapper is configured, we may be able to map in an externally authenticated user - String userId = getRemoteUser(sc, httpRequest); - - final WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(sc); - HttpSession session = httpRequest.getSession(); - User user = null; - - // examine the appropriate session to try and find the User object - SessionUser sessionUser = Application.getCurrentUser(session); - - // Make sure the ticket is valid, the person exists, and the cached user is of the right type (WebDAV users have - // been known to leak in but shouldn't now) - if (sessionUser != null) - { - if (logger.isDebugEnabled()) - logger.debug("SessionUser is: " + sessionUser.getUserName()); - AuthenticationService auth = (AuthenticationService) wc.getBean(AUTHENTICATION_SERVICE); - try - { - auth.validate(sessionUser.getTicket()); - if (sessionUser instanceof User) - { - user = (User)sessionUser; - setExternalAuth(session, userId != null); - } - else - { - user = setUser(sc, httpRequest, sessionUser.getUserName(), sessionUser.getTicket(), userId != null); - } - } - catch (AuthenticationException authErr) - { - if (logger.isDebugEnabled()) - logger.debug("An authentication error occured while setting the session user", authErr); - session.removeAttribute(AUTHENTICATION_USER); - if (!Application.inPortalServer()) - { - if (logger.isDebugEnabled()) - logger.debug("Invalidating the session."); - session.invalidate(); - } - } - } - - // If the remote user mapper is configured, we may be able to map in an externally authenticated user - if (userId != null) - { - AuthorityService authorityService = (AuthorityService) wc.getBean(AUTHORITY_SERVICE); - // We have a previously-cached user with the wrong identity - replace them - if (user != null && !authorityService.isGuestAuthority(user.getUserName()) && !user.getUserName().equals(userId)) - { - if (logger.isDebugEnabled()) - logger.debug("We have a previously-cached user with the wrong identity - replace them"); - session.removeAttribute(AUTHENTICATION_USER); - if (!Application.inPortalServer()) - { - if (logger.isDebugEnabled()) - logger.debug("Invalidating session."); - session.invalidate(); - } - user = null; - } - - if (user == null) - { - if (logger.isDebugEnabled()) - logger.debug("There are no previously-cached users."); - // If we have been authenticated by other means, just propagate through the user identity - AuthenticationComponent authenticationComponent = (AuthenticationComponent) wc - .getBean(AUTHENTICATION_COMPONENT); - try - { - if (logger.isDebugEnabled()) - logger.debug("We have been authenticated by other means, authenticating the user: " + userId); - authenticationComponent.setCurrentUser(userId); - AuthenticationService authenticationService = (AuthenticationService) wc.getBean(AUTHENTICATION_SERVICE); - user = setUser(sc, httpRequest, userId, authenticationService.getCurrentTicket(), true); - } - catch (AuthenticationException authErr) - { - if (logger.isDebugEnabled()) - logger.debug("An authentication error occured while setting the session user" , authErr); - // Allow for an invalid external user ID to be indicated - session.removeAttribute(AUTHENTICATION_USER); - if (!Application.inPortalServer()) - { - if (logger.isDebugEnabled()) - logger.debug("Invalidating the session."); - session.invalidate(); - } - } - } - } - return user; - } - - /** - * Setup the Alfresco auth cookie value. - * - * @param httpRequest - * @param httpResponse - * @param username - */ - public static void setUsernameCookie(HttpServletRequest httpRequest, HttpServletResponse httpResponse, String username) - { - if (logger.isDebugEnabled()) - logger.debug("Setting up the Alfresco auth cookie for " + username); - Cookie authCookie = getAuthCookie(httpRequest); - // Let's Base 64 encode the username so it is a legal cookie value - String encodedUsername; - try - { - encodedUsername = Base64.encodeBytes(username.getBytes("UTF-8")); - if (logger.isDebugEnabled()) - logger.debug("Base 64 encode the username: " + encodedUsername); - } - catch (UnsupportedEncodingException e) - { - throw new RuntimeException(e); - } - if (authCookie == null) - { - if (logger.isDebugEnabled()) - logger.debug("No Alfresco auth cookie wa found, creating new one."); - authCookie = new Cookie(COOKIE_ALFUSER, encodedUsername); - } - else - { - if (logger.isDebugEnabled()) - logger.debug("Updating the previous Alfresco auth cookie value."); - authCookie.setValue(encodedUsername); - } - authCookie.setPath(httpRequest.getContextPath()); - // TODO: make this configurable - currently 7 days (value in seconds) - authCookie.setMaxAge(60*60*24*7); - httpResponse.addCookie(authCookie); - } - - /** - * Helper to return the Alfresco auth cookie. The cookie saves the last used username value. - * - * @param httpRequest - * - * @return Cookie if found or null if not present - */ - public static Cookie getAuthCookie(HttpServletRequest httpRequest) - { - if (logger.isDebugEnabled()) - logger.debug("Searching for Alfresco auth cookie."); - Cookie authCookie = null; - Cookie[] cookies = httpRequest.getCookies(); - if (cookies != null) - { - if (logger.isDebugEnabled()) - logger.debug("Cookies present."); - for (int i=0; i. - * #L% - */ -package org.alfresco.web.app.servlet; - -/** - * @author Kevin Roast - */ -public enum AuthenticationStatus -{ - Success, Failure, Guest; -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/BaseDownloadContentServlet.java b/war/src/main/java/org/alfresco/web/app/servlet/BaseDownloadContentServlet.java deleted file mode 100644 index b00c98752b..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/BaseDownloadContentServlet.java +++ /dev/null @@ -1,455 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; -import java.net.SocketException; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.StringTokenizer; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.content.filestore.FileContentReader; -import org.alfresco.repo.web.util.HttpRangeProcessor; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.model.FileInfo; -import org.alfresco.service.cmr.model.FileNotFoundException; -import org.alfresco.service.cmr.repository.ContentIOException; -import org.alfresco.service.cmr.repository.ContentReader; -import org.alfresco.service.cmr.repository.ContentService; -import org.alfresco.service.cmr.repository.MimetypeService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.repository.StoreRef; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.apache.commons.logging.Log; -import org.springframework.extensions.surf.util.URLDecoder; -import org.springframework.extensions.surf.util.URLEncoder; -import org.springframework.extensions.webscripts.ui.common.StringUtils; - -/** - * Base class for the download content servlets. Provides common - * processing for the request. - * - * @see org.alfresco.web.app.servlet.DownloadContentServlet - * @see org.alfresco.web.app.servlet.GuestDownloadContentServlet - * - * @author Kevin Roast - * @author gavinc - */ -public abstract class BaseDownloadContentServlet extends BaseServlet -{ - private static final String HEADER_IF_MODIFIED_SINCE = "If-Modified-Since"; - - private static final long serialVersionUID = -4558907921887235967L; - - private static final String POWER_POINT_DOCUMENT_MIMETYPE = "application/vnd.ms-powerpoint"; - private static final String POWER_POINT_2007_DOCUMENT_MIMETYPE = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; - - private static final String HEADER_CONTENT_RANGE = "Content-Range"; - private static final String HEADER_CONTENT_LENGTH = "Content-Length"; - private static final String HEADER_ACCEPT_RANGES = "Accept-Ranges"; - private static final String HEADER_RANGE = "Range"; - private static final String HEADER_ETAG = "ETag"; - private static final String HEADER_CACHE_CONTROL = "Cache-Control"; - private static final String HEADER_LAST_MODIFIED = "Last-Modified"; - private static final String HEADER_USER_AGENT = "User-Agent"; - private static final String HEADER_CONTENT_DISPOSITION = "Content-Disposition"; - - protected static final String MIMETYPE_OCTET_STREAM = "application/octet-stream"; - - protected static final String MSG_ERROR_CONTENT_MISSING = "error_content_missing"; - protected static final String MSG_ERROR_NOT_FOUND = "error_not_found"; - - protected static final String URL_DIRECT = "d"; - protected static final String URL_DIRECT_LONG = "direct"; - protected static final String URL_ATTACH = "a"; - protected static final String URL_ATTACH_LONG = "attach"; - protected static final String ARG_PROPERTY = "property"; - protected static final String ARG_PATH = "path"; - - /** - * Gets the logger to use for this request. - *

- * This will show all debug entries from this class as though they - * came from the subclass. - * - * @return The logger - */ - protected abstract Log getLogger(); - - /** - * Processes the download request using the current context i.e. no authentication checks are made, it is presumed - * they have already been done. - * - * @param req - * The HTTP request - * @param res - * The HTTP response - * @param allowLogIn - * Indicates whether guest users without access to the content should be redirected to the log in page. If - * false, a status 403 forbidden page is displayed instead. - */ - protected void processDownloadRequest(HttpServletRequest req, HttpServletResponse res, - boolean allowLogIn, boolean transmitContent) - throws ServletException, IOException - { - Log logger = getLogger(); - String uri = req.getRequestURI(); - - if (logger.isDebugEnabled()) - { - String queryString = req.getQueryString(); - logger.debug("Processing URL: " + uri + - ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : "")); - } - - uri = uri.substring(req.getContextPath().length()); - StringTokenizer t = new StringTokenizer(uri, "/"); - int tokenCount = t.countTokens(); - - t.nextToken(); // skip servlet name - - // attachment mode (either 'attach' or 'direct') - String attachToken = t.nextToken(); - boolean attachment = URL_ATTACH.equals(attachToken) || URL_ATTACH_LONG.equals(attachToken); - - ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext()); - - // get or calculate the noderef and filename to download as - NodeRef nodeRef; - String filename; - - // do we have a path parameter instead of a NodeRef? - String path = req.getParameter(ARG_PATH); - if (path != null && path.length() != 0) - { - // process the name based path to resolve the NodeRef and the Filename element - try - { - PathRefInfo pathInfo = resolveNamePath(getServletContext(), path); - nodeRef = pathInfo.NodeRef; - filename = pathInfo.Filename; - } - catch (IllegalArgumentException e) - { - Application.handleSystemError(getServletContext(), req, res, MSG_ERROR_NOT_FOUND, - HttpServletResponse.SC_NOT_FOUND, logger); - return; - } - } - else - { - // a NodeRef must have been specified if no path has been found - if (tokenCount < 6) - { - throw new IllegalArgumentException("Download URL did not contain all required args: " + uri); - } - - // assume 'workspace' or other NodeRef based protocol for remaining URL elements - StoreRef storeRef = new StoreRef(URLDecoder.decode(t.nextToken()), URLDecoder.decode(t.nextToken())); - String id = URLDecoder.decode(t.nextToken()); - - // build noderef from the appropriate URL elements - nodeRef = new NodeRef(storeRef, id); - - if (tokenCount > 6) - { - // found additional relative path elements i.e. noderefid/images/file.txt - // this allows a url to reference siblings nodes via a cm:name based relative path - // solves the issue with opening HTML content containing relative URLs in HREF or IMG tags etc. - List paths = new ArrayList(tokenCount - 5); - while (t.hasMoreTokens()) - { - paths.add(URLDecoder.decode(t.nextToken())); - } - filename = paths.get(paths.size() - 1); - - try - { - NodeRef parentRef = serviceRegistry.getNodeService().getPrimaryParent(nodeRef).getParentRef(); - FileInfo fileInfo = serviceRegistry.getFileFolderService().resolveNamePath(parentRef, paths); - nodeRef = fileInfo.getNodeRef(); - } - catch (FileNotFoundException e) - { - Application.handleSystemError(getServletContext(), req, res, MSG_ERROR_NOT_FOUND, - HttpServletResponse.SC_NOT_FOUND, logger); - return; - } - } - else - { - // filename is last remaining token - filename = t.nextToken(); - } - } - - // get qualified of the property to get content from - default to ContentModel.PROP_CONTENT - QName propertyQName = ContentModel.PROP_CONTENT; - String property = req.getParameter(ARG_PROPERTY); - if (property != null && property.length() != 0) - { - propertyQName = QName.createQName(property); - } - - if (logger.isDebugEnabled()) - { - logger.debug("Found NodeRef: " + nodeRef); - logger.debug("Will use filename: " + filename); - logger.debug("For property: " + propertyQName); - logger.debug("With attachment mode: " + attachment); - } - - // get the services we need to retrieve the content - NodeService nodeService = serviceRegistry.getNodeService(); - ContentService contentService = serviceRegistry.getContentService(); - - // Check that the node still exists - if (!nodeService.exists(nodeRef)) - { - Application.handleSystemError(getServletContext(), req, res, MSG_ERROR_NOT_FOUND, - HttpServletResponse.SC_NOT_FOUND, logger); - return; - } - - try - { - // check that the user has at least READ_CONTENT access - else redirect to an error or login page - if (!checkAccess(req, res, nodeRef, PermissionService.READ_CONTENT, allowLogIn)) - { - return; - } - - // check If-Modified-Since header and set Last-Modified header as appropriate - Date modified = (Date)nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIED); - if (modified != null) - { - long modifiedSince = req.getDateHeader(HEADER_IF_MODIFIED_SINCE); - if (modifiedSince > 0L) - { - // round the date to the ignore millisecond value which is not supplied by header - long modDate = (modified.getTime() / 1000L) * 1000L; - if (modDate <= modifiedSince) - { - if (logger.isDebugEnabled()) - logger.debug("Returning 304 Not Modified."); - res.setStatus(HttpServletResponse.SC_NOT_MODIFIED); - return; - } - } - res.setDateHeader(HEADER_LAST_MODIFIED, modified.getTime()); - res.setHeader(HEADER_CACHE_CONTROL, "must-revalidate, max-age=0"); - res.setHeader(HEADER_ETAG, "\"" + Long.toString(modified.getTime()) + "\""); - } - - if (attachment == true) - { - setHeaderContentDisposition(req, res, filename); - } - - // get the content reader - ContentReader reader = contentService.getReader(nodeRef, propertyQName); - // ensure that it is safe to use - reader = FileContentReader.getSafeContentReader( - reader, - Application.getMessage(req.getSession(), MSG_ERROR_CONTENT_MISSING), - nodeRef, reader); - - String mimetype = reader.getMimetype(); - // fall back if unable to resolve mimetype property - if (mimetype == null || mimetype.length() == 0) - { - MimetypeService mimetypeMap = serviceRegistry.getMimetypeService(); - mimetype = MIMETYPE_OCTET_STREAM; - int extIndex = filename.lastIndexOf('.'); - if (extIndex != -1) - { - String ext = filename.substring(extIndex + 1); - mimetype = mimetypeMap.getMimetype(ext); - } - } - - // explicitly set the content disposition header if the content is powerpoint - if (!attachment && (mimetype.equals(POWER_POINT_2007_DOCUMENT_MIMETYPE) || - mimetype.equals(POWER_POINT_DOCUMENT_MIMETYPE))) - { - setHeaderContentDisposition(req, res, filename); - } - - // get the content and stream directly to the response output stream - // assuming the repo is capable of streaming in chunks, this should allow large files - // to be streamed directly to the browser response stream. - res.setHeader(HEADER_ACCEPT_RANGES, "bytes"); - - // for a GET request, transmit the content else just the headers are sent - if (transmitContent) - { - try - { - boolean processedRange = false; - String range = req.getHeader(HEADER_CONTENT_RANGE); - if (range == null) - { - range = req.getHeader(HEADER_RANGE); - } - if (range != null) - { - if (logger.isDebugEnabled()) - logger.debug("Found content range header: " + range); - - // ensure the range header is starts with "bytes=" and process the range(s) - if (range.length() > 6) - { - HttpRangeProcessor rangeProcessor = new HttpRangeProcessor(contentService); - processedRange = rangeProcessor.processRange( - res, reader, range.substring(6), nodeRef, propertyQName, - mimetype, req.getHeader(HEADER_USER_AGENT)); - } - } - if (processedRange == false) - { - if (logger.isDebugEnabled()) - logger.debug("Sending complete file content..."); - - // set mimetype for the content and the character encoding for the stream - res.setContentType(mimetype); - res.setCharacterEncoding(reader.getEncoding()); - - // MNT-10642 Alfresco Explorer has javascript vulnerability opening HTML files - if (req.getRequestURI().contains("/d/d/") && (mimetype.equals("text/html") || mimetype.equals("application/xhtml+xml") || mimetype.equals("text/xml"))) - { - String content = reader.getContentString(); - - if (mimetype.equals("text/html") || mimetype.equals("application/xhtml+xml")) - { - // process with HTML stripper - content = StringUtils.stripUnsafeHTMLTags(content, false); - } - else if (mimetype.equals("text/xml") && mimetype.equals("text/x-component")) - { - // IE supports "behaviour" which means that css can load a .htc file that could - // contain XSS code in the form of jscript, vbscript etc, to stop it form being - // evaluated we set the contient type to text/plain - res.setContentType("text/plain"); - } - - String encoding = reader.getEncoding(); - byte[] bytes = encoding != null ? content.getBytes(encoding) : content.getBytes(); - res.setContentLength(bytes.length); - res.getOutputStream().write(bytes); - - return; - } - - // return the complete entity range - long size = reader.getSize(); - res.setHeader(HEADER_CONTENT_RANGE, "bytes 0-" + Long.toString(size-1L) + "/" + Long.toString(size)); - res.setHeader(HEADER_CONTENT_LENGTH, Long.toString(size)); - reader.getContent( res.getOutputStream() ); - } - } - catch (SocketException e1) - { - // the client cut the connection - our mission was accomplished apart from a little error message - if (logger.isDebugEnabled()) - logger.debug("Client aborted stream read:\n\tnode: " + nodeRef + "\n\tcontent: " + reader); - } - catch (ContentIOException e2) - { - if (logger.isInfoEnabled()) - logger.info("Failed stream read:\n\tnode: " + nodeRef + " due to: " + e2.getMessage()); - } - catch (Throwable err) - { - if (err.getCause() instanceof SocketException) - { - // the client cut the connection - our mission was accomplished apart from a little error message - if (logger.isDebugEnabled()) - logger.debug("Client aborted stream read:\n\tnode: " + nodeRef + "\n\tcontent: " + reader); - } - else throw err; - } - } - else - { - if (logger.isDebugEnabled()) - logger.debug("HEAD request processed - no content sent."); - res.getOutputStream().close(); - } - } - catch (Throwable err) - { - throw new AlfrescoRuntimeException("Error during download content servlet processing: " + err.getMessage(), err); - } - } - - private void setHeaderContentDisposition(HttpServletRequest req, HttpServletResponse res, String filename) - { - // set header based on filename - will force a Save As from the browse if it doesn't recognise it - // this is better than the default response of the browser trying to display the contents - - // IE requires that "Content-Disposition" header in case of "attachment" type should include - // "filename" part. See MNT-9900 - String userAgent = req.getHeader(HEADER_USER_AGENT); - if (userAgent != null && (userAgent.toLowerCase().contains("firefox") || userAgent.toLowerCase().contains("safari"))) - { - res.setHeader(HEADER_CONTENT_DISPOSITION, "attachment; filename=\"" + URLDecoder.decode(filename) + "\""); - } - else - { - res.setHeader(HEADER_CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\""); - } - - } - - /** - * Helper to generate a URL to a content node for downloading content from the server. - * - * @param pattern The pattern to use for the URL - * @param ref NodeRef of the content node to generate URL for (cannot be null) - * @param name File name to return in the URL (cannot be null) - * - * @return URL to download the content from the specified node - */ - protected final static String generateUrl(String pattern, NodeRef ref, String name) - { - return MessageFormat.format(pattern, new Object[] { - ref.getStoreRef().getProtocol(), - ref.getStoreRef().getIdentifier(), - ref.getId(), - URLEncoder.encode(name) } ); - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/BaseServlet.java b/war/src/main/java/org/alfresco/web/app/servlet/BaseServlet.java deleted file mode 100644 index 04b4d059b2..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/BaseServlet.java +++ /dev/null @@ -1,507 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; -import java.io.PrintWriter; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.StringTokenizer; - -import javax.faces.context.FacesContext; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork; -import org.alfresco.repo.tenant.TenantService; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.model.FileFolderService; -import org.alfresco.service.cmr.model.FileInfo; -import org.alfresco.service.cmr.model.FileNotFoundException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.search.SearchService; -import org.alfresco.service.cmr.security.AccessStatus; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.LoginOutcomeBean; -import org.alfresco.web.bean.repository.Repository; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.extensions.surf.util.URLDecoder; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.WebApplicationContextUtils; -import org.springframework.web.jsf.FacesContextUtils; - - -/** - * Base servlet class containing useful constant values and common methods for Alfresco servlets. - * - * @author Kevin Roast - */ -public abstract class BaseServlet extends HttpServlet -{ - private static final long serialVersionUID = -826295358696861789L; - - public static final String FACES_SERVLET = "/faces"; - public static final String KEY_STORE = "store"; - public static final String KEY_ROOT_PATH = "rootPath"; - - /** an existing Ticket can be passed to most servlet for non-session based authentication */ - private static final String ARG_TICKET = "ticket"; - - /** forcing guess access is available on most servlets */ - private static final String ARG_GUEST = "guest"; - - private static final String MSG_ERROR_PERMISSIONS = "error_permissions"; - - /** list of valid JSPs for redirect after a clean login */ - // TODO: make this list configurable - private static Set validRedirectJSPs = new HashSet(); - static - { - validRedirectJSPs.add("/jsp/browse/browse.jsp"); - validRedirectJSPs.add("/jsp/admin/admin-console.jsp"); - validRedirectJSPs.add("/jsp/admin/avm-console.jsp"); - validRedirectJSPs.add("/jsp/admin/node-browser.jsp"); - validRedirectJSPs.add("/jsp/admin/store-browser.jsp"); - validRedirectJSPs.add("/jsp/users/user-console.jsp"); - validRedirectJSPs.add("/jsp/categories/categories.jsp"); - validRedirectJSPs.add("/jsp/dialog/about.jsp"); - validRedirectJSPs.add("/jsp/search/advanced-search.jsp"); - validRedirectJSPs.add("/jsp/admin/system-info.jsp"); - validRedirectJSPs.add("/jsp/forums/forums.jsp"); - validRedirectJSPs.add("/jsp/users/users.jsp"); - validRedirectJSPs.add("/jsp/trashcan/trash-list.jsp"); - } - - private static Log logger = LogFactory.getLog(BaseServlet.class); - - - /** - * Return the ServiceRegistry helper instance - * - * @param sc ServletContext - * - * @return ServiceRegistry - */ - public static ServiceRegistry getServiceRegistry(ServletContext sc) - { - WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(sc); - return (ServiceRegistry)wc.getBean(ServiceRegistry.SERVICE_REGISTRY); - } - - /** - * Perform an authentication for the servlet request URI. Processing any "ticket" or - * "guest" URL arguments. - * - * @return AuthenticationStatus - * - * @throws IOException - */ - public AuthenticationStatus servletAuthenticate(HttpServletRequest req, HttpServletResponse res) - throws IOException - { - return servletAuthenticate(req, res, true); - } - - /** - * Perform an authentication for the servlet request URI. Processing any "ticket" or - * "guest" URL arguments. - * - * @return AuthenticationStatus - * - * @throws IOException - */ - public AuthenticationStatus servletAuthenticate(HttpServletRequest req, HttpServletResponse res, - boolean redirectToLoginPage) throws IOException - { - AuthenticationStatus status; - - // see if a ticket or a force Guest parameter has been supplied - String ticket = req.getParameter(ARG_TICKET); - if (ticket != null && ticket.length() != 0) - { - status = AuthenticationHelper.authenticate(getServletContext(), req, res, ticket); - } - else - { - boolean forceGuest = false; - String guest = req.getParameter(ARG_GUEST); - if (guest != null) - { - forceGuest = Boolean.parseBoolean(guest); - } - status = AuthenticationHelper.authenticate(getServletContext(), req, res, forceGuest); - } - if (status == AuthenticationStatus.Failure && redirectToLoginPage) - { - // authentication failed - now need to display the login page to the user, if asked to - redirectToLoginPage(req, res, getServletContext()); - } - - return status; - } - - /** - * Check the user has the given permission on the given node. If they do not either force a log on if this is a guest - * user or forward to an error page. - * - * @param req - * the request - * @param res - * the response - * @param nodeRef - * the node in question - * @param allowLogIn - * Indicates whether guest users without access to the node should be redirected to the log in page. If - * false, a status 403 forbidden page is displayed instead. - * @return true, if the user has access - * @throws IOException - * Signals that an I/O exception has occurred. - * @throws ServletException - * On other errors - */ - public boolean checkAccess(HttpServletRequest req, HttpServletResponse res, NodeRef nodeRef, String permission, - boolean allowLogIn) throws IOException, ServletException - { - ServletContext sc = getServletContext(); - ServiceRegistry serviceRegistry = getServiceRegistry(sc); - PermissionService permissionService = serviceRegistry.getPermissionService(); - - // check that the user has the permission - if (permissionService.hasPermission(nodeRef, permission) == AccessStatus.DENIED) - { - if (logger.isDebugEnabled()) - logger.debug("User does not have " + permission + " permission for NodeRef: " + nodeRef.toString()); - - if (allowLogIn && serviceRegistry.getAuthorityService().hasGuestAuthority()) - { - if (logger.isDebugEnabled()) - logger.debug("Redirecting to login page..."); - redirectToLoginPage(req, res, sc); - } - else - { - if (logger.isDebugEnabled()) - logger.debug("Forwarding to error page..."); - Application - .handleSystemError(sc, req, res, MSG_ERROR_PERMISSIONS, HttpServletResponse.SC_FORBIDDEN, logger); - } - return false; - } - return true; - } - - /** - * Redirect to the Login page - saving the current URL which can be redirected back later - * once the user has successfully completed the authentication process. - */ - public static void redirectToLoginPage(HttpServletRequest req, HttpServletResponse res, ServletContext sc) - throws IOException - { - redirectToLoginPage(req, res, sc, AuthenticationHelper.getRemoteUserMapper(sc) == null); - } - - /** - * Redirect to the Login page - saving the current URL which can be redirected back later - * once the user has successfully completed the authentication process. - * @param sendRedirect allow a redirect status code to be set? If false redirect - * will be via markup rather than status code (to allow the status code to be used for handshake - * responses etc. - */ - public static void redirectToLoginPage(HttpServletRequest req, HttpServletResponse res, ServletContext sc, boolean sendRedirect) - throws IOException - { - // Pass the full requested URL as a parameter so the login page knows where to redirect to later - final String uri = req.getRequestURI(); - String redirectURL = uri; - - // authentication failed - so end servlet execution and redirect to login page - if (WebApplicationContextUtils.getRequiredWebApplicationContext(sc).containsBean(Application.BEAN_CONFIG_SERVICE)) - { - StringBuilder redirect = new StringBuilder(128) - .append(req.getContextPath()).append(FACES_SERVLET).append(Application.getLoginPage(sc)); - - // if we find a JSF servlet reference in the URI then we need to check if the rest of the - // JSP specified is valid for a redirect operation after Login has occured. - int jspIndex; - if (uri.indexOf(req.getContextPath() + FACES_SERVLET) == -1 - || uri.length() > (jspIndex = uri.indexOf(BaseServlet.FACES_SERVLET) + BaseServlet.FACES_SERVLET.length()) - && BaseServlet.validRedirectJSP(uri.substring(jspIndex))) - { - if (redirect.indexOf("?") == -1) - { - redirect.append('?'); - } - else - { - redirect.append('&'); - } - redirect.append(LoginOutcomeBean.PARAM_REDIRECT_URL); - redirect.append('='); - String url = uri; - - // Append the query string if necessary - String queryString = req.getQueryString(); - if (queryString != null) - { - // Strip out leading ticket arguments - queryString = queryString.replaceAll("(?<=^|&)" + ARG_TICKET + "(=[^&=]*)?&", ""); - // Strip out trailing ticket arguments - queryString = queryString.replaceAll("(^|&)" + ARG_TICKET + "(=[^&=]*)?(?=&|$)", ""); - if (queryString.length() != 0) - { - url += "?" + queryString; - } - } - redirect.append(URLEncoder.encode(url, "UTF-8")); - } - redirectURL = redirect.toString(); - } - // If external authentication isn't in use (e.g. proxied share authentication), it's safe to return a redirect to the client - if (sendRedirect) - { - res.sendRedirect(redirectURL); - } - // Otherwise, we must signal to the client with an unauthorized status code and rely on a browser refresh to do - // the redirect for failover login (as we do with NTLM, Kerberos) - else - { - res.setContentType("text/html; charset=UTF-8"); - res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - - final PrintWriter out = res.getWriter(); - out.println(""); - // Remove the auto refresh to avoid refresh loop, MNT-16931 -// out.println(""); - out.println("

Please log in.

"); - out.println(""); - out.close(); - } - } - - /** - * Apply the headers required to disallow caching of the response in the browser - */ - public static void setNoCacheHeaders(HttpServletResponse res) - { - res.setHeader("Cache-Control", "no-cache"); - res.setHeader("Pragma", "no-cache"); - } - - /** - * Returns true if the specified JSP file is valid for a redirect after login. - * Only a specific sub-set of the available JSPs are valid to jump directly too after a - * clean login attempt - e.g. those that do not require JSF bean context setup. This is - * a limitation of the JSP architecture. The ExternalAccessServlet provides a mechanism to - * setup the JSF bean context directly for some specific cases. - * - * @param jsp Filename of JSP to check, for example "/jsp/browse/browse.jsp" - * - * @return true if the JSP is in the list of valid direct URLs, false otherwise - */ - public static boolean validRedirectJSP(String jsp) - { - return validRedirectJSPs.contains(jsp); - } - - /** - * Resolves the given path elements to a NodeRef in the current repository - * - * @param context Faces context - * @param args The elements of the path to lookup - */ - public static NodeRef resolveWebDAVPath(FacesContext context, String[] args) - { - WebApplicationContext wc = FacesContextUtils.getRequiredWebApplicationContext(context); - return resolveWebDAVPath(wc, args, true); - } - - /** - * Resolves the given path elements to a NodeRef in the current repository - * - * @param context Faces context - * @param args The elements of the path to lookup - * @param decode True to decode the arg from UTF-8 format, false for no decoding - */ - public static NodeRef resolveWebDAVPath(FacesContext context, String[] args, boolean decode) - { - WebApplicationContext wc = FacesContextUtils.getRequiredWebApplicationContext(context); - return resolveWebDAVPath(wc, args, decode); - } - - /** - * Resolves the given path elements to a NodeRef in the current repository - * - * @param context ServletContext context - * @param args The elements of the path to lookup - */ - public static NodeRef resolveWebDAVPath(ServletContext context, String[] args) - { - WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(context); - return resolveWebDAVPath(wc, args, true); - } - - /** - * Resolves the given path elements to a NodeRef in the current repository - * - * @param context ServletContext context - * @param args The elements of the path to lookup - * @param decode True to decode the arg from UTF-8 format, false for no decoding - */ - public static NodeRef resolveWebDAVPath(ServletContext context, String[] args, boolean decode) - { - WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(context); - return resolveWebDAVPath(wc, args, decode); - } - - /** - * Resolves the given path elements to a NodeRef in the current repository - * - * @param wc WebApplicationContext Context - * @param args The elements of the path to lookup - * @param decode True to decode the arg from UTF-8 format, false for no decoding - */ - private static NodeRef resolveWebDAVPath(final WebApplicationContext wc, final String[] args, final boolean decode) - { - return AuthenticationUtil.runAs(new RunAsWork() - { - public NodeRef doWork() throws Exception - { - NodeRef nodeRef = null; - - List paths = new ArrayList(args.length - 1); - - FileInfo file = null; - try - { - // create a list of path elements (decode the URL as we go) - for (int x = 1; x < args.length; x++) - { - paths.add(decode ? URLDecoder.decode(args[x]) : args[x]); - } - - if (logger.isDebugEnabled()) - logger.debug("Attempting to resolve webdav path: " + paths); - - // get the company home node to start the search from - nodeRef = new NodeRef(Repository.getStoreRef(), Application.getCompanyRootId()); - - TenantService tenantService = (TenantService)wc.getBean("tenantService"); - if (tenantService != null && tenantService.isEnabled()) - { - if (logger.isDebugEnabled()) - logger.debug("MT is enabled."); - - NodeService nodeService = (NodeService) wc.getBean("NodeService"); - SearchService searchService = (SearchService) wc.getBean("SearchService"); - NamespaceService namespaceService = (NamespaceService) wc.getBean("NamespaceService"); - - // TODO: since these constants are used more widely than just the WebDAVServlet, - // they should be defined somewhere other than in that servlet - String rootPath = wc.getServletContext().getInitParameter(BaseServlet.KEY_ROOT_PATH); - - // note: rootNodeRef is required (for storeRef part) - nodeRef = tenantService.getRootNode(nodeService, searchService, namespaceService, rootPath, nodeRef); - } - - if (paths.size() != 0) - { - FileFolderService ffs = (FileFolderService)wc.getBean("FileFolderService"); - file = ffs.resolveNamePath(nodeRef, paths); - nodeRef = file.getNodeRef(); - } - - if (logger.isDebugEnabled()) - logger.debug("Resolved webdav path to NodeRef: " + nodeRef); - } - catch (FileNotFoundException fne) - { - if (logger.isWarnEnabled()) - logger.warn("Failed to resolve webdav path", fne); - - nodeRef = null; - } - return nodeRef; - } - }, AuthenticationUtil.getSystemUserName()); - } - - /** - * Resolve a name based into a NodeRef and Filename string - * - * @param sc ServletContext - * @param path 'cm:name' based path using the '/' character as a separator - * - * @return PathRefInfo structure containing the resolved NodeRef and filename - * - * @throws IllegalArgumentException - */ - public final static PathRefInfo resolveNamePath(ServletContext sc, String path) - { - StringTokenizer t = new StringTokenizer(path, "/"); - int tokenCount = t.countTokens(); - String[] elements = new String[tokenCount]; - for (int i=0; i. - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.SocketException; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import java.util.StringTokenizer; - -import javax.faces.context.FacesContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.transaction.UserTransaction; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.security.permissions.AccessDeniedException; -import org.alfresco.repo.web.scripts.FileTypeImageUtils; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.FileTypeImageSize; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.repository.StoreRef; -import org.alfresco.service.cmr.repository.TemplateException; -import org.alfresco.service.cmr.repository.TemplateImageResolver; -import org.alfresco.service.cmr.repository.TemplateService; -import org.alfresco.service.cmr.security.AccessStatus; -import org.alfresco.service.cmr.security.PermissionService; -import org.apache.commons.logging.Log; - -/** - * Base class for the template content servlets. Provides common - * processing for the request. - * - * @see org.alfresco.web.app.servlet.TemplateContentServlet - * @see org.alfresco.web.app.servlet.GuestTemplateContentServlet - * - * @author Kevin Roast - * @author gavinc - */ -@SuppressWarnings("serial") -public abstract class BaseTemplateContentServlet extends BaseServlet -{ - private static final String MIMETYPE_HTML = "text/html;charset=utf-8"; - - private static final long serialVersionUID = -4123407921997235977L; - - private static final String ARG_MIMETYPE = "mimetype"; - private static final String ARG_TEMPLATE_PATH = "templatePath"; - private static final String ARG_CONTEXT_PATH = "contextPath"; - - /** - * Gets the logger to use for this request. - *

- * This will show all debug entries from this class as though they - * came from the subclass. - * - * @return The logger - */ - protected abstract Log getLogger(); - - /** - * Builds the FreeMarker model - * - * @param services Service Registry instance - * @param req Http request - * @param templateRef The node ref of the template to process - * @return The FreeMarker model - */ - protected abstract Map buildModel(ServiceRegistry services, - HttpServletRequest req, NodeRef templateRef); - - /** - * Processes the template request using the current context i.e. no - * authentication checks are made, it is presumed they have already - * been done. - * - * @param req The HTTP request - * @param res The HTTP response - * @param redirectToLogin Flag to determine whether to redirect to the login - * page if the user does not have the correct permissions - */ - protected void processTemplateRequest(HttpServletRequest req, HttpServletResponse res, - boolean redirectToLogin) throws ServletException, IOException - { - Log logger = getLogger(); - String uri = req.getRequestURI(); - - if (logger.isDebugEnabled()) - { - String queryString = req.getQueryString(); - logger.debug("Processing URL: " + uri + - ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : "")); - } - - uri = uri.substring(req.getContextPath().length()); - StringTokenizer t = new StringTokenizer(uri, "/"); - int tokenCount = t.countTokens(); - - t.nextToken(); // skip servlet name - - NodeRef nodeRef = null; - NodeRef templateRef = null; - - try - { - String contentPath = req.getParameter(ARG_CONTEXT_PATH); - if (contentPath != null && contentPath.length() != 0) - { - // process the name based path to resolve the NodeRef - PathRefInfo pathInfo = resolveNamePath(getServletContext(), contentPath); - - nodeRef = pathInfo.NodeRef; - } - else if (tokenCount > 3) - { - // get NodeRef to the content from the URL elements - StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken()); - nodeRef = new NodeRef(storeRef, t.nextToken()); - } - - // get NodeRef to the template if supplied - String templatePath = req.getParameter(ARG_TEMPLATE_PATH); - if (templatePath != null && templatePath.length() != 0) - { - // process the name based path to resolve the NodeRef - PathRefInfo pathInfo = resolveNamePath(getServletContext(), templatePath); - - templateRef = pathInfo.NodeRef; - } - else if (tokenCount >= 7) - { - StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken()); - templateRef = new NodeRef(storeRef, t.nextToken()); - } - } - catch (AccessDeniedException err) - { - if (redirectToLogin) - { - if (logger.isDebugEnabled()) - logger.debug("Redirecting to login page..."); - - redirectToLoginPage(req, res, getServletContext()); - } - else - { - if (logger.isDebugEnabled()) - logger.debug("Returning 403 Forbidden error..."); - - res.sendError(HttpServletResponse.SC_FORBIDDEN); - } - - return; - } - - // if no context is specified, use the template itself - // TODO: should this default to something else? - if (nodeRef == null && templateRef != null) - { - nodeRef = templateRef; - } - - if (nodeRef == null) - { - throw new TemplateException("Not enough elements supplied in URL or no 'path' argument specified."); - } - - // get the services we need to retrieve the content - ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext()); - NodeService nodeService = serviceRegistry.getNodeService(); - TemplateService templateService = serviceRegistry.getTemplateService(); - PermissionService permissionService = serviceRegistry.getPermissionService(); - - // check that the user has at least READ access on any nodes - else redirect to the login page - if (permissionService.hasPermission(nodeRef, PermissionService.READ) == AccessStatus.DENIED || - (templateRef != null && permissionService.hasPermission(templateRef, PermissionService.READ) == AccessStatus.DENIED)) - { - if (redirectToLogin) - { - if (logger.isDebugEnabled()) - logger.debug("Redirecting to login page..."); - - redirectToLoginPage(req, res, getServletContext()); - } - else - { - if (logger.isDebugEnabled()) - logger.debug("Returning 403 Forbidden error..."); - - res.sendError(HttpServletResponse.SC_FORBIDDEN); - } - - return; - } - - String mimetype = MIMETYPE_HTML; - if (req.getParameter(ARG_MIMETYPE) != null) - { - mimetype = req.getParameter(ARG_MIMETYPE); - } - res.setContentType(mimetype); - - try - { - UserTransaction txn = null; - try - { - txn = serviceRegistry.getTransactionService().getUserTransaction(true); - txn.begin(); - - // if template not supplied, then use the default against the node - if (templateRef == null) - { - if (nodeService.hasAspect(nodeRef, ContentModel.ASPECT_TEMPLATABLE)) - { - templateRef = (NodeRef)nodeService.getProperty(nodeRef, ContentModel.PROP_TEMPLATE); - } - if (templateRef == null) - { - throw new TemplateException("Template reference not set against node or not supplied in URL."); - } - } - - // create the model - put the supplied noderef in as space/document as appropriate - Map model = getModel(serviceRegistry, req, templateRef, nodeRef); - - // process the template against the node content directly to the response output stream - // assuming the repo is capable of streaming in chunks, this should allow large files - // to be streamed directly to the browser response stream. - try - { - templateService.processTemplate( - templateRef.toString(), - model, - res.getWriter()); - - // commit the transaction - txn.commit(); - } - catch (SocketException e) - { - if (e.getMessage().contains("ClientAbortException")) - { - // the client cut the connection - our mission was accomplished apart from a little error message - logger.error("Client aborted stream read:\n node: " + nodeRef + "\n template: " + templateRef); - try { if (txn != null) {txn.rollback();} } catch (Exception tex) {} - } - else - { - throw e; - } - } - finally - { - res.getWriter().close(); - } - } - catch (Throwable txnErr) - { - try { if (txn != null) {txn.rollback();} } catch (Exception tex) {} - throw txnErr; - } - } - catch (Throwable err) - { - throw new AlfrescoRuntimeException("Error during template servlet processing: " + err.getMessage(), err); - } - } - - /** - * Build the model that to process the template against. - *

- * The model includes the usual template root objects such as 'companyhome', 'userhome', - * 'person' and also includes the node specified on the servlet URL as 'space' and 'document' - * - * @param services ServiceRegistry - * @param req Http request - for accessing Session and url args - * @param templateRef NodeRef of the template itself - * @param nodeRef NodeRef of the space/document to process template against - * - * @return an object model ready for executing template against - */ - @SuppressWarnings("unchecked") - private Map getModel(ServiceRegistry services, HttpServletRequest req, NodeRef templateRef, NodeRef nodeRef) - { - // build FreeMarker default model and merge - Map root = buildModel(services, req, templateRef); - - // put the current NodeRef in as "space" and "document" - root.put("space", nodeRef); - root.put("document", nodeRef); - - // add URL arguments as a map called 'args' to the root of the model - Map args = new HashMap(8, 1.0f); - Enumeration names = req.getParameterNames(); - while (names.hasMoreElements()) - { - String name = (String)names.nextElement(); - try - { - args.put(name, new String(req.getParameter(name).getBytes(), "UTF-8")); - } - catch (UnsupportedEncodingException err) {} - } - root.put("args", args); - - // Add the image resolver - root.put(TemplateService.KEY_IMAGE_RESOLVER, imageResolver); - - // method to allow client urls to be generated - root.put("url", new URLHelper(req)); - - return root; - } - - /** Template Image resolver helper */ - protected TemplateImageResolver imageResolver = new TemplateImageResolver() - { - public String resolveImagePathForName(String filename, FileTypeImageSize size) - { - return FileTypeImageUtils.getFileTypeImage(getServletContext(), filename, size); - } - }; - - /** - * Helper to return context path for generating urls - */ - public static class URLHelper - { - String contextPath; - String serverPath; - - public URLHelper(HttpServletRequest request) - { - this.contextPath = request.getContextPath(); - this.serverPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); - } - - public URLHelper(FacesContext context) - { - this.contextPath = context.getExternalContext().getRequestContextPath(); - final Object request = context.getExternalContext().getRequest(); - if (request instanceof HttpServletRequest) - { - final HttpServletRequest httpServletRequest = (HttpServletRequest) request; - this.serverPath = httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort(); - } - } - - public String getContext() - { - return this.contextPath; - } - - public String getServerPath() - { - return this.serverPath; - } - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/CmisSecurityContextCleanerFilter.java b/war/src/main/java/org/alfresco/web/app/servlet/CmisSecurityContextCleanerFilter.java deleted file mode 100644 index 7c962950d8..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/CmisSecurityContextCleanerFilter.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - -import net.sf.acegisecurity.context.ContextHolder; - -/** - * Clears security context. It should follow Authentication filters in the chain and should be mapped for CMIS requests only - * - * @author Dmitry Velichkevich - * @since 4.1.5 - */ -public class CmisSecurityContextCleanerFilter implements Filter -{ - @Override - public void destroy() - { - } - - @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException - { - ContextHolder.setContext(null); - chain.doFilter(servletRequest, servletResponse); - } - - @Override - public void init(FilterConfig config) throws ServletException - { - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/CommandServlet.java b/war/src/main/java/org/alfresco/web/app/servlet/CommandServlet.java deleted file mode 100644 index b1a64b8513..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/CommandServlet.java +++ /dev/null @@ -1,273 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; -import java.io.PrintWriter; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import java.util.StringTokenizer; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.transaction.UserTransaction; - -import org.springframework.extensions.config.Config; -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.servlet.command.CommandFactory; -import org.alfresco.web.app.servlet.command.CommandProcessor; -import org.alfresco.web.app.servlet.command.ExtCommandProcessor; -import org.alfresco.web.config.CommandServletConfigElement; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Servlet responsible for executing commands upon node(s). - *

- * The URL to the servlet should be generated thus: - *

/alfresco/command/processor-name/command-name/args/...
- *

- * The 'processor-name' identifies the command processor to execute the command. For example the - * 'workflow' processor will execute workflow commands upon a node (e.g. "approve" or "reject"). - * For example: - *

/alfresco/command/workflow/approve/workspace/SpacesStore/0000-0000-0000-0000
- * The store protocol, followed by the store ID, followed by the content Node Id used to - * identify the node to execute the workflow action upon. - *

- * A 'return-page' URL argument can be specified as the redirect page to navigate too after processing. - *

- * Like most Alfresco servlets, the URL may be followed by a valid 'ticket' argument for authentication: - * ?ticket=1234567890 - *

- * And/or also followed by the "?guest=true" argument to force guest access login for the URL. - * - * @author Kevin Roast - * @deprecated 5.0 not exposed in web-client web.xml - */ -public class CommandServlet extends BaseServlet -{ - private static final long serialVersionUID = -5432407921038376133L; - - private static Log logger = LogFactory.getLog(CommandServlet.class); - - private static CommandFactory commandfactory = CommandFactory.getInstance(); - - public static final String ARG_RETURNPAGE = "return-page"; - - /** - * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - protected void service(HttpServletRequest req, HttpServletResponse res) - throws ServletException, IOException - { - String uri = req.getRequestURI(); - - if (logger.isDebugEnabled()) - logger.debug("Processing URL: " + uri + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "")); - - AuthenticationStatus status = servletAuthenticate(req, res); - if (status == AuthenticationStatus.Failure) - { - return; - } - - setNoCacheHeaders(res); - - uri = uri.substring(req.getContextPath().length()); - StringTokenizer t = new StringTokenizer(uri, "/"); - int tokenCount = t.countTokens(); - if (tokenCount < 3) - { - throw new IllegalArgumentException("Command Servlet URL did not contain all required args: " + uri); - } - - t.nextToken(); // skip servlet name - - // get the command processor to execute the command e.g. "workflow" - String procName = t.nextToken(); - - // get the command to perform - String command = t.nextToken(); - - // get any remaining uri elements to pass to the processor - String[] urlElements = new String[tokenCount - 3]; - for (int i=0; i args = new HashMap(8, 1.0f); - Enumeration names = req.getParameterNames(); - while (names.hasMoreElements()) - { - String name = (String)names.nextElement(); - args.put(name, req.getParameter(name)); - } - - try - { - // get configured command processor by name from Config Service - CommandProcessor processor = createCommandProcessor(procName); - - // validate that the processor has everything it needs to run the command - if (processor.validateArguments(getServletContext(), command, args, urlElements) == false) - { - redirectToLoginPage(req, res, getServletContext()); - return; - } - - ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext()); - UserTransaction txn = null; - try - { - txn = serviceRegistry.getTransactionService().getUserTransaction(); - txn.begin(); - - // inform the processor to execute the specified command - if (processor instanceof ExtCommandProcessor) - { - ((ExtCommandProcessor)processor).process(serviceRegistry, req, res, command); - } - else - { - processor.process(serviceRegistry, req, command); - } - - // commit the transaction - txn.commit(); - } - catch (Throwable txnErr) - { - try { if (txn != null) {txn.rollback();} } catch (Exception tex) {} - throw txnErr; - } - - String returnPage = req.getParameter(ARG_RETURNPAGE); - if (returnPage != null && returnPage.length() != 0) - { - validateReturnPage(returnPage, req); - if (logger.isDebugEnabled()) - logger.debug("Redirecting to specified return page: " + returnPage); - - res.sendRedirect(returnPage); - } - else - { - if (logger.isDebugEnabled()) - logger.debug("No return page specified, displaying status output."); - - if (res.getContentType() == null && !res.isCommitted()) - { - res.setContentType("text/html"); - - // request that the processor output a useful status message - PrintWriter out = res.getWriter(); - processor.outputStatus(out); - out.close(); - } - } - } - catch (Throwable err) - { - throw new AlfrescoRuntimeException("Error during command servlet processing: " + err.getMessage(), err); - } - } - - /** - * ALF-9113 CommandServlet.java, line 179 (Header Manipulation) - * - * Validates that the redirect page is within the current context. - * - * Examples of valid redirect pages: - *

    - *
  • /alfresco/faces/jsp/browse/browse.jsp
  • - *
  • ../../browse/browse.jsp
  • - *
- * - * @param pageUrl - * @param req - * @throws MalformedURLException - * @throws IllegalArgumentException - */ - private void validateReturnPage(String pageUrl, HttpServletRequest req) throws MalformedURLException - { - if (pageUrl.indexOf(':') != -1) - { - // ':' only allowed in a URL as part of a scheme prefix - throw new IllegalArgumentException("The redirect URL doesn't support absolute URls"); - } - // Evaluate it relative to the request URL and strip out .. and . - pageUrl = new URL(new URL(req.getRequestURL().toString()), pageUrl).getPath(); - if (!pageUrl.startsWith(req.getContextPath())) - { - throw new IllegalArgumentException("The redirect URL must be in the same context."); - } - } - - /** - * Created the specified CommandProcessor instance. The name of the processor is looked up - * in the client config, it should find a valid class impl and then create it. - * - * @param procName Name of the CommandProcessor to lookup in the client config. - * - * @return CommandProcessor - * - * @throws InstantiationException - * @throws IllegalAccessException - */ - private CommandProcessor createCommandProcessor(String procName) - throws InstantiationException, IllegalAccessException - { - Config config = Application.getConfigService(getServletContext()).getConfig("Command Servlet"); - if (config == null) - { - throw new AlfrescoRuntimeException("No command processors configured - unable to process any commands."); - } - - CommandServletConfigElement configElement = (CommandServletConfigElement) - config.getConfigElement(CommandServletConfigElement.CONFIG_ELEMENT_ID); - if (configElement == null) - { - throw new AlfrescoRuntimeException("No command processors configured - unable to process any commands."); - } - - Class clazz = configElement.getCommandProcessor(procName); - Object obj = clazz.newInstance(); - if (obj instanceof CommandProcessor == false) - { - throw new AlfrescoRuntimeException("Configured command processor '" + procName + "' is does not implement interface CommandProcessor!"); - } - - return (CommandProcessor)obj; - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/DownloadContentServlet.java b/war/src/main/java/org/alfresco/web/app/servlet/DownloadContentServlet.java deleted file mode 100644 index 0939b19fc6..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/DownloadContentServlet.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.transaction.TransactionService; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Servlet responsible for streaming node content from the repo directly to the response stream. - * The appropriate mimetype is calculated based on filename extension. - *

- * The URL to the servlet should be generated thus: - *

/alfresco/download/attach/workspace/SpacesStore/0000-0000-0000-0000/myfile.pdf
- * or - *
/alfresco/download/direct/workspace/SpacesStore/0000-0000-0000-0000/myfile.pdf
- * or - *
/alfresco/download/[direct|attach]?path=/Company%20Home/MyFolder/myfile.pdf
- * The protocol, followed by either the store and Id (NodeRef) or instead specify a name based - * encoded Path to the content, note that the filename element is used for mimetype lookup and - * as the returning filename for the response stream. - *

- * The 'attach' or 'direct' element is used to indicate whether to display the stream directly - * in the browser or download it as a file attachment. - *

- * By default, the download assumes that the content is on the - * {@link org.alfresco.model.ContentModel#PROP_CONTENT content property}.
- * To retrieve the content of a specific model property, use a 'property' arg, providing the workspace, - * node ID AND the qualified name of the property. - *

- * Like most Alfresco servlets, the URL may be followed by a valid 'ticket' argument for authentication: - * ?ticket=1234567890 - *

- * And/or also followed by the "?guest=true" argument to force guest access login for the URL. If the - * guest=true parameter is used the current session will be logged out and the guest user logged in. - * Therefore upon completion of this request the current user will be "guest". - *

- * If the user attempting the request is not authorised to access the requested node the login page - * will be redirected to. - * - * @author Kevin Roast - * @author gavinc - */ -public class DownloadContentServlet extends BaseDownloadContentServlet -{ - private static final long serialVersionUID = -576405943603122206L; - - private static Log logger = LogFactory.getLog(DownloadContentServlet.class); - - private static final String DOWNLOAD_URL = "/d/" + URL_ATTACH + "/{0}/{1}/{2}/{3}"; - private static final String BROWSER_URL = "/d/" + URL_DIRECT + "/{0}/{1}/{2}/{3}"; - - @Override - protected Log getLogger() - { - return logger; - } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpServlet#doHead(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - protected void doHead(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException - { - if (logger.isDebugEnabled()) - { - String queryString = req.getQueryString(); - logger.debug("Authenticating (HEAD) request to URL: " + req.getRequestURI() + - ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : "")); - } - - AuthenticationStatus status = servletAuthenticate(req, res); - if (status == AuthenticationStatus.Failure) - { - return; - } - - ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext()); - TransactionService transactionService = serviceRegistry.getTransactionService(); - RetryingTransactionCallback processCallback = new RetryingTransactionCallback() - { - public Void execute() throws Throwable - { - processDownloadRequest(req, res, true, false); - return null; - } - }; - transactionService.getRetryingTransactionHelper().doInTransaction(processCallback, true); - } - - /** - * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - protected void doGet(final HttpServletRequest req, final HttpServletResponse res) - throws ServletException, IOException - { - if (logger.isDebugEnabled()) - { - String queryString = req.getQueryString(); - logger.debug("Authenticating (GET) request to URL: " + req.getRequestURI() + - ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : "")); - } - - AuthenticationStatus status = servletAuthenticate(req, res); - if (status == AuthenticationStatus.Failure) - { - return; - } - - ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext()); - TransactionService transactionService = serviceRegistry.getTransactionService(); - RetryingTransactionCallback processCallback = new RetryingTransactionCallback() - { - public Void execute() throws Throwable - { - processDownloadRequest(req, res, true, true); - return null; - } - }; - transactionService.getRetryingTransactionHelper().doInTransaction(processCallback, true); - } - - /** - * Helper to generate a URL to a content node for downloading content from the server. - * The content is supplied as an HTTP1.1 attachment to the response. This generally means - * a browser should prompt the user to save the content to specified location. - * - * @param ref NodeRef of the content node to generate URL for (cannot be null) - * @param name File name to return in the URL (cannot be null) - * - * @return URL to download the content from the specified node - */ - public final static String generateDownloadURL(NodeRef ref, String name) - { - return generateUrl(DOWNLOAD_URL, ref, name); - } - - /** - * Helper to generate a URL to a content node for downloading content from the server. - * The content is supplied directly in the reponse. This generally means a browser will - * attempt to open the content directly if possible, else it will prompt to save the file. - * - * @param ref NodeRef of the content node to generate URL for (cannot be null) - * @param name File name to return in the URL (cannot be null) - * - * @return URL to download the content from the specified node - */ - public final static String generateBrowserURL(NodeRef ref, String name) - { - return generateUrl(BROWSER_URL, ref, name); - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/DownloadRawContentServlet.java b/war/src/main/java/org/alfresco/web/app/servlet/DownloadRawContentServlet.java deleted file mode 100644 index 2db42dbcf3..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/DownloadRawContentServlet.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; -import java.io.OutputStream; -import java.net.SocketException; -import java.util.Date; -import java.util.Locale; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.repo.security.permissions.AccessDeniedException; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.ContentIOException; -import org.alfresco.service.cmr.repository.ContentReader; -import org.alfresco.service.cmr.repository.ContentService; -import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * A serlet that provides direct access to the content stores via a content URL. - *

- * Requests can be of the form:
- *

- * /alfresco/downloadDirect?contentUrl=some-url?ticket=auth?infoOnly=value
- *    contentUrl is a ContentStore-specific URL 
- *    ticket is a valid authentication token for an admin user 
- *    infoOnly is set to true to leave off the binary stream and just send
- *                    the data about the content. 
- * 
- * This serlet is intended to be accessed to retrieve the binary content from - * the content stores. If you wish to retrieve content from a client, use - * the other content download servlets available. - *

- * The following responses are generated: - *

    - *
  • Contet not found: 204 NO CONTENT
  • - *
  • Access denied: 403 FORBIDDEN
  • - *
- * The following header values are set: - *
    - *
  • alfresco.dr.size: The content size
  • - *
  • alfresco.dr.lastModified: The last modified date
  • - *
  • alfresco.dr.mimetype: The content mimetype
  • - *
  • alfresco.dr.encoding: The content encoding
  • - *
  • alfresco.dr.locale: The content locale
  • - *
- * Note that the mimetype, encoding and locale generally fallback to the default - * as implemented by the {@linkplain ContentService#getRawReader(String) raw reader}. - * - * @since 2.1 - * @author Derek Hulley - */ -public class DownloadRawContentServlet extends BaseServlet -{ - private static final long serialVersionUID = 2973080032044411358L; - - private static Log logger = LogFactory.getLog(DownloadRawContentServlet.class); - - private static final String DEFAULT_MIMETYPE = MimetypeMap.MIMETYPE_BINARY; - private static final String DEFAULT_ENCODING = "utf-8"; - - private static final String ARG_CONTENT_URL = "contentUrl"; - private static final String ARG_INFO_ONLY = "infoOnly"; - - protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException - { - if (logger.isDebugEnabled()) - { - logger.debug("Authenticating downloadDirect request: " + req.getRequestURI()); - } - - AuthenticationStatus status = servletAuthenticate(req, res); - if (status == AuthenticationStatus.Failure) - { - return; - } - - setNoCacheHeaders(res); - - processRequest(req, res); - } - - /** - * Processes the request using the current context i.e. no - * authentication checks are made, it is presumed they have already - * been done. - * - * @param req The HTTP request - * @param res The HTTP response - */ - private void processRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException - { - String uri = req.getRequestURI(); - - String contentUrl = req.getParameter(ARG_CONTENT_URL); - if (contentUrl == null || contentUrl.length() == 0) - { - throw new IllegalArgumentException("Download URL did not contain parameter '" + ARG_CONTENT_URL + "':" + uri); - } - String infoOnlyStr = req.getParameter(ARG_INFO_ONLY); - boolean infoOnly = (infoOnlyStr == null) ? false : Boolean.parseBoolean(infoOnlyStr); - - ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext()); - ContentService contentService = serviceRegistry.getContentService(); - - // Attempt to get the reader - ContentReader reader = null; - try - { - reader = contentService.getRawReader(contentUrl); - // If the content doesn't exist, generate an error - if (!reader.exists()) - { - if (logger.isDebugEnabled()) - { - logger.debug("Returning 204 Not Found error..."); - } - res.sendError(HttpServletResponse.SC_NO_CONTENT); - return; - } - } - catch (AccessDeniedException e) - { - if (logger.isDebugEnabled()) - { - logger.debug("Returning 403 Forbidden error after exception: ", e); - } - res.sendError(HttpServletResponse.SC_FORBIDDEN); - return; - } - - long readerSize = reader.getSize(); - Date readerLastModified = new Date(reader.getLastModified()); - String readerMimetype = reader.getMimetype(); - String readerEncoding = reader.getEncoding(); - Locale readerLocale = reader.getLocale(); - // Set the content info - res.setHeader("alfresco.dr.size", DefaultTypeConverter.INSTANCE.convert(String.class, readerSize)); - res.setHeader("alfresco.dr.lastModified", DefaultTypeConverter.INSTANCE.convert(String.class, readerLastModified)); - res.setHeader("alfresco.dr.mimetype", readerMimetype); - res.setHeader("alfresco.dr.encoding", readerEncoding); - res.setHeader("alfresco.dr.locale", DefaultTypeConverter.INSTANCE.convert(String.class, readerLocale)); - - // Pass the stream to the response, unless only the content info was requested - if (infoOnly) - { - // Fill response details - res.setContentType(DEFAULT_MIMETYPE); - res.setCharacterEncoding(DEFAULT_ENCODING); - } - else - { - // Fill response details - res.setContentType(readerMimetype); - res.setCharacterEncoding(readerEncoding); - - try - { - OutputStream clientOs = res.getOutputStream(); - reader.getContent( clientOs ); // Streams closed for us - } - catch (SocketException e1) - { - // Not a problem - if (logger.isDebugEnabled()) - { - logger.debug( - "Client aborted stream read:\n" + - " Content URL: " + contentUrl); - } - } - catch (ContentIOException e2) - { - // Not a problem - if (logger.isDebugEnabled()) - { - logger.debug( - "Client aborted stream read:\n" + - " Content URL: " + contentUrl); - } - } - } - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/ExternalAccessServlet.java b/war/src/main/java/org/alfresco/web/app/servlet/ExternalAccessServlet.java deleted file mode 100644 index be6be0dfb8..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/ExternalAccessServlet.java +++ /dev/null @@ -1,360 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; -import java.text.MessageFormat; -import java.util.Stack; -import java.util.StringTokenizer; - -import javax.faces.application.NavigationHandler; -import javax.faces.context.FacesContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.repo.webdav.WebDAVServlet; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.StoreRef; -import org.alfresco.service.cmr.security.AccessStatus; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.BrowseBean; -import org.alfresco.web.bean.NavigationBean; -import org.alfresco.web.bean.dashboard.DashboardManager; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.myfaces.shared_impl.renderkit.ViewSequenceUtils; - -/** - * Servlet allowing external URL access to various global JSF views in the Web Client. - *

- * The servlet accepts a well formed URL that can easily be generated from a Content or Space NodeRef. - * The URL also specifies the JSF "outcome" to be executed which provides the correct JSF View to be - * displayed. The JSF "outcome" must equate to a global navigation rule or it will not be displayed. - * Servlet URL is of the form: - *

- * http://<server>/alfresco/navigate/<outcome>[/<workspace>/<store>/<nodeId>] or
- * http://<server>/alfresco/navigate/<outcome>[/webdav/<path/to/node>] - *

- * Like most Alfresco servlets, the URL may be followed by a valid 'ticket' argument for authentication: - * ?ticket=1234567890 - *

- * And/or also followed by the "?guest=true" argument to force guest access login for the URL. - * - * @author Kevin Roast - * @deprecated 5.0 not exposed in web-client web.xml - */ -public class ExternalAccessServlet extends BaseServlet -{ - private static final long serialVersionUID = -4118907921337237802L; - - private static Log logger = LogFactory.getLog(ExternalAccessServlet.class); - - public final static String OUTCOME_DOCDETAILS = "showDocDetails"; - public final static String OUTCOME_SPACEDETAILS = "showSpaceDetails"; - public final static String OUTCOME_BROWSE = "browse"; - public final static String OUTCOME_MYALFRESCO = "myalfresco"; - public final static String OUTCOME_LOGOUT = "logout"; - public final static String OUTCOME_DIALOG = "dialog"; - public final static String OUTCOME_WIZARD = "wizard"; - - private static final String ARG_TEMPLATE = "template"; - private static final String ARG_PAGE = "page"; - - /** - * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - protected void service(HttpServletRequest req, HttpServletResponse res) - throws ServletException, IOException - { - String uri = req.getRequestURI(); - - if (logger.isDebugEnabled()) - logger.debug("Processing URL: " + uri + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "")); - - AuthenticationStatus status = servletAuthenticate(req, res); - if (status == AuthenticationStatus.Failure) - { - return; - } - - setNoCacheHeaders(res); - - uri = uri.substring(req.getContextPath().length()); - StringTokenizer t = new StringTokenizer(uri, "/"); - int tokenCount = t.countTokens(); - if (tokenCount < 2) - { - throw new IllegalArgumentException("Externally addressable URL did not contain all required args: " + uri); - } - - t.nextToken(); // skip servlet name - - String outcome = t.nextToken(); - - // get rest of the tokens arguments - String[] args = new String[tokenCount - 2]; - for (int i=0; i= 3) - { - int offset = 0; - - offset = args.length - 3; - StoreRef storeRef = new StoreRef(args[0+offset], args[1+offset]); - nodeRef = new NodeRef(storeRef, args[2+offset]); - } - - if (nodeRef != null) - { - // check that the user has at least READ access - else redirect to an error or login page - if (!checkAccess(req, res, nodeRef, PermissionService.READ_CONTENT, true)) - { - return; - } - - // this call sets up the current node Id, and updates or initialises the - // breadcrumb component with the selected node as appropriate. - browseBean.updateUILocation(nodeRef); - - // force a "late" refresh of the BrowseBean to handle external servlet access URL - browseBean.externalAccessRefresh(); - - // check for view mode first argument - if (args[0].equals(ARG_TEMPLATE)) - { - browseBean.setDashboardView(true); - } - - // the above calls into BrowseBean setup the NavigationHandler automatically - } - else - { - // perform the appropriate JSF navigation outcome - NavigationHandler navigationHandler = fc.getApplication().getNavigationHandler(); - navigationHandler.handleNavigation(fc, null, outcome); - } - } - else if (OUTCOME_MYALFRESCO.equals(outcome)) - { - // setup the Dashboard Manager ready for the page we want to display - if (req.getParameter(ARG_PAGE) != null) - { - DashboardManager manager = (DashboardManager)FacesHelper.getManagedBean(fc, DashboardManager.BEAN_NAME); - manager.getPageConfig().setCurrentPage(req.getParameter(ARG_PAGE)); - } - - // perform the appropriate JSF navigation outcome - NavigationHandler navigationHandler = fc.getApplication().getNavigationHandler(); - navigationHandler.handleNavigation(fc, null, outcome); - } - else if (OUTCOME_DIALOG.equals(outcome) || OUTCOME_WIZARD.equals(outcome)) - { - if (args.length != 0) - { - if (args.length > 1) - { - String currentNodeId = null; - - if (args[1].equals(WebDAVServlet.WEBDAV_PREFIX)) - { - // Drop the first argument - String[] args2 = new String[ args.length -1 ]; - for (int i=1; i/alfresco/navigate/[///] - private static final String EXTERNAL_URL = "/n/{0}"; - private static final String EXTERNAL_URL_ARGS = "/n/{0}/{1}"; -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/FacesHelper.java b/war/src/main/java/org/alfresco/web/app/servlet/FacesHelper.java deleted file mode 100644 index dace6afb82..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/FacesHelper.java +++ /dev/null @@ -1,345 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import javax.faces.FactoryFinder; -import javax.faces.component.UIComponent; -import javax.faces.component.UIViewRoot; -import javax.faces.context.FacesContext; -import javax.faces.context.FacesContextFactory; -import javax.faces.el.EvaluationException; -import javax.faces.el.ValueBinding; -import javax.faces.lifecycle.Lifecycle; -import javax.faces.lifecycle.LifecycleFactory; -import javax.servlet.ServletContext; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.web.bean.generator.IComponentGenerator; -import org.alfresco.web.ui.repo.RepoConstants; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * @author Kevin Roast - */ -public final class FacesHelper -{ - /** Root browse screen JSF view ID */ - public static final String BROWSE_VIEW_ID = "/jsp/browse/browse.jsp"; - - private static Log logger = LogFactory.getLog(FacesHelper.class); - - /** - * Mask for hex encoding - */ - private static final int MASK = (1 << 4) - 1; - - /** - * Digits used for hex string encoding - */ - private static final char[] DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; - - - /** - * Private constructor - */ - private FacesHelper() - { - } - - /** - * Return a valid FacesContext for the specific context, request and response. - * The FacesContext can be constructor for Servlet use. - * - * @param context ServletContext - * @param request ServletRequest - * @param response ServletReponse - * - * @return FacesContext - */ - public static FacesContext getFacesContext(ServletRequest request, ServletResponse response, ServletContext context) - { - return getFacesContextImpl(request, response, context, null); - } - - /** - * Return a valid FacesContext for the specific context, request and response. - * The FacesContext can be constructor for Servlet use. - * - * @param context ServletContext - * @param request ServletRequest - * @param response ServletReponse - * - * @return FacesContext - */ - public static FacesContext getFacesContext(ServletRequest request, ServletResponse response, ServletContext context, String viewRoot) - { - return getFacesContextImpl(request, response, context, viewRoot); - } - - /** - * Return a valid FacesContext for the specific context, request and response. - * The FacesContext can be constructor for Servlet use. - * - * @param context PortletContext - * @param request PortletRequest - * @param response PortletResponse - * - * @return FacesContext - */ - public static FacesContext getFacesContext(Object request, Object response, Object context) - { - return getFacesContextImpl(request, response, context, null); - } - - /** - * Return a valid FacesContext for the specific context, request and response. - * The FacesContext can be constructor for Servlet and Portlet use. - * - * @param context ServletContext or PortletContext - * @param request ServletRequest or PortletRequest - * @param response ServletReponse or PortletResponse - * - * @return FacesContext - */ - private static FacesContext getFacesContextImpl(Object request, Object response, Object context, String viewRoot) - { - FacesContextFactory contextFactory = (FacesContextFactory)FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY); - LifecycleFactory lifecycleFactory = (LifecycleFactory)FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY); - Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE); - - // Doesn't set this instance as the current instance of FacesContext.getCurrentInstance - FacesContext facesContext = contextFactory.getFacesContext(context, request, response, lifecycle); - - // Set using our inner class - InnerFacesContext.setFacesContextAsCurrent(facesContext); - - // set a new viewRoot, otherwise context.getViewRoot returns null - if (viewRoot == null) - { - viewRoot = FacesHelper.BROWSE_VIEW_ID; - } - - UIViewRoot view = facesContext.getApplication().getViewHandler().createView(facesContext, viewRoot); - facesContext.setViewRoot(view); - - return facesContext; - } - - /** - * Return a JSF managed bean reference. - * - * @param fc FacesContext - * @param name Name of the managed bean to return - * - * @return the managed bean or null if not found - */ - public static Object getManagedBean(FacesContext fc, String name) - { - Object obj = null; - - try - { - ValueBinding vb = fc.getApplication().createValueBinding("#{" + name + "}"); - obj = vb.getValue(fc); - } - catch (EvaluationException ee) - { - // catch exception to resolve ADB-158/ACT-7343 - // not much we can do here, just make sure return is null - if (logger.isDebugEnabled()) - logger.debug("Failed to resolve managed bean: " + name, ee); - obj = null; - } - - return obj; - } - - /** - * Sets up the id for the given component, if the id is null a unique one - * is generated using the standard Faces algorithm. If an id is present it - * is checked for illegal characters. - * - * @param context FacesContext - * @param component The component to set the id for - * @param id The id to set - */ - public static void setupComponentId(FacesContext context, UIComponent component, String id) - { - if (id == null) - { - id = context.getViewRoot().createUniqueId(); - } - else - { - // make sure we do not have illegal characters in the id - id = makeLegalId(id); - } - - component.setId(id); - } - - /** - * Makes the given id a legal JSF component id by replacing illegal characters - * with ISO9075 encoding - which itself a subset of valid HTML ID characters. - * - * @param id The id to make legal - * - * @return the legalised id - */ - public static String makeLegalId(String id) - { - return (id != null ? validFacesId(id) : null); - } - - /** - * Retrieves the named component generator implementation. - * If the named generator is not found the TextFieldGenerator is looked up - * as a default, if this is also not found an AlfrescoRuntimeException is thrown. - * - * @param context FacesContext - * @param generatorName The name of the component generator to retrieve - * @return The component generator instance - */ - public static IComponentGenerator getComponentGenerator(FacesContext context, String generatorName) - { - IComponentGenerator generator = lookupComponentGenerator(context, generatorName); - - if (generator == null) - { - // create a text field if we can't find a component generator (a warning should have already been - // displayed on the appserver console) - - logger.warn("Attempting to find default component generator '" + RepoConstants.GENERATOR_TEXT_FIELD + "'"); - generator = lookupComponentGenerator(context, RepoConstants.GENERATOR_TEXT_FIELD); - } - - // if we still don't have a component generator we should abort as vital configuration is missing - if (generator == null) - { - throw new AlfrescoRuntimeException("Failed to find a component generator, please ensure the '" + - RepoConstants.GENERATOR_TEXT_FIELD + "' bean is present in your configuration"); - } - - return generator; - } - - private static IComponentGenerator lookupComponentGenerator(FacesContext context, String generatorName) - { - IComponentGenerator generator = null; - - Object obj = FacesHelper.getManagedBean(context, generatorName); - if (obj != null) - { - if (obj instanceof IComponentGenerator) - { - generator = (IComponentGenerator)obj; - - if (logger.isDebugEnabled()) - logger.debug("Found component generator for '" + generatorName + "': " + generator); - } - else - { - logger.warn("Bean '" + generatorName + "' does not implement IComponentGenerator"); - } - } - else - { - logger.warn("Failed to find component generator with name of '" + generatorName + "'"); - } - - return generator; - } - - /** - * We need an inner class to be able to call FacesContext.setCurrentInstance - * since it's a protected method - */ - private abstract static class InnerFacesContext extends FacesContext - { - protected static void setFacesContextAsCurrent(FacesContext facesContext) - { - FacesContext.setCurrentInstance(facesContext); - } - } - - /** - * Helper to ensure only valid and acceptable characters are output as Faces component IDs. - * Based on ISO9075 encoding - which itself a subset of valid HTML ID characters. - */ - private static String validFacesId(String id) - { - int len = id.length(); - StringBuilder buf = new StringBuilder(len + (len>>1)); - for (int i = 0; i= 65 && ci <= 90) || // A-Z - (ci >= 97 && ci <= 122)) // a-z - { - buf.append(c); - } - else - { - encode(c, buf); - } - } - else - { - if ((ci >= 65 && ci <= 90) || // A-Z - (ci >= 97 && ci <= 122) || // a-z - (ci >= 48 && ci <= 57) || // 0-9 - ci == 45 || ci == 95) // - and _ - { - buf.append(c); - } - else - { - encode(c, buf); - } - } - } - return buf.toString(); - } - - private static void encode(char c, StringBuilder builder) - { - char[] buf = new char[] { 'x', '0', '0', '0', '0', '_' }; - int charPos = 5; - do - { - buf[--charPos] = DIGITS[c & MASK]; - c >>>= 4; - } - while (c != 0); - builder.append(buf); - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/GlobalLocalizationFilter.java b/war/src/main/java/org/alfresco/web/app/servlet/GlobalLocalizationFilter.java deleted file mode 100644 index 41dc64cb24..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/GlobalLocalizationFilter.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; -import java.util.Locale; -import java.util.StringTokenizer; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; - -import org.springframework.extensions.surf.util.I18NUtil; - -/** - * @author Stas Sokolovsky - * - * Servlet filter responsible for setting a fallback default locale for ALL requests. - */ -public class GlobalLocalizationFilter implements Filter -{ - /** - * Run the filter - * - * @param request ServletRequest - * @param response ServletResponse - * @param chain FilterChain - * @exception IOException - * @exception ServletException - */ - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException - { - // Clear content locale from this thread (it may be set later) - I18NUtil.setContentLocale(null); - - setLanguageFromRequestHeader((HttpServletRequest) request); - - // continue filter chaining - chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response){ - - /* (non-Javadoc) - * @see javax.servlet.ServletResponseWrapper#setContentType(java.lang.String) - */ - @Override - public void setContentType(String type) - { - super.setContentType(type); - - // Parse the parameters of the media type, since some app servers (Websphere) refuse to pay attention if the - // character encoding isn't explicitly set - int startIndex = type.indexOf(';') + 1; - int length = type.length(); - while (startIndex != 0 && startIndex < length) - { - int endIndex = type.indexOf(';', startIndex); - if (endIndex == -1) - { - endIndex = length; - } - String param = type.substring(startIndex, endIndex); - int sepIndex = param.indexOf('='); - if (sepIndex != -1) - { - String name = param.substring(0, sepIndex).trim(); - if (name.equalsIgnoreCase("charset")) - { - String charset = param.substring(sepIndex + 1).trim(); - if ((null != charset) && ((charset.startsWith("\"") && charset.endsWith("\"")) || (charset.startsWith("'") && charset.endsWith("'")))) - { - charset = charset.substring(1, (charset.length() - 1)); - } - setCharacterEncoding(charset); - break; - } - } - startIndex = endIndex + 1; - } - } - }); - - } - - /** - * Apply Client and Repository language locale based on the 'Accept-Language' request header - * - * @param req HttpServletRequest - */ - public void setLanguageFromRequestHeader(HttpServletRequest req) - { - Locale locale = null; - - String acceptLang = req.getHeader("Accept-Language"); - if (acceptLang != null && acceptLang.length() > 0) - { - StringTokenizer tokenizer = new StringTokenizer(acceptLang, ",; "); - // get language and convert to java locale format - String language = tokenizer.nextToken().replace('-', '_'); - locale = I18NUtil.parseLocale(language); - I18NUtil.setLocale(locale); - } - else - { - I18NUtil.setLocale(Locale.getDefault()); - } - } - - public void init(FilterConfig filterConfig) throws ServletException - { - // Nothing to do - } - - public void destroy() - { - // Nothing to do - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/GuestDownloadContentServlet.java b/war/src/main/java/org/alfresco/web/app/servlet/GuestDownloadContentServlet.java deleted file mode 100644 index d4c2a452c8..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/GuestDownloadContentServlet.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork; -import org.alfresco.service.cmr.repository.NodeRef; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Servlet responsible for streaming node content from the repo directly to the response stream. - * The appropriate mimetype is calculated based on filename extension. - *

- * The URL to the servlet should be generated thus: - *

/alfresco/guestDownload/attach/workspace/SpacesStore/0000-0000-0000-0000/myfile.pdf
- * or - *
/alfresco/guestDownload/direct/workspace/SpacesStore/0000-0000-0000-0000/myfile.pdf
- * or - *
/alfresco/guestDownload/[direct|attach]?path=/Company%20Home/MyFolder/myfile.pdf
- * The protocol, followed by either the store and Id (NodeRef) or instead specify a name based - * encoded Path to the content, note that the filename element is used for mimetype lookup and - * as the returning filename for the response stream. - *

- * The 'attach' or 'direct' element is used to indicate whether to display the stream directly - * in the browser or download it as a file attachment. - *

- * By default, the download assumes that the content is on the - * {@link org.alfresco.model.ContentModel#PROP_CONTENT content property}.
- * To retrieve the content of a specific model property, use a 'property' arg, providing the workspace, - * node ID AND the qualified name of the property. - *

- * This servlet only accesses content available to the guest user. If the guest user does not - * have access to the requested a 403 Forbidden response is returned to the caller. - *

- * This servlet does not effect the current session, therefore if guest access is required to a - * resource this servlet can be used without logging out the current user. - * - * @author gavinc - */ -public class GuestDownloadContentServlet extends BaseDownloadContentServlet -{ - private static final long serialVersionUID = -5258137503339817457L; - - private static Log logger = LogFactory.getLog(GuestDownloadContentServlet.class); - - private static final String DOWNLOAD_URL = "/gd/" + URL_ATTACH + "/{0}/{1}/{2}/{3}"; - private static final String BROWSER_URL = "/gd/" + URL_DIRECT + "/{0}/{1}/{2}/{3}"; - - @Override - protected Log getLogger() - { - return logger; - } - - /** - * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - protected void doGet(HttpServletRequest req, HttpServletResponse res) - throws ServletException, IOException - { - if (logger.isDebugEnabled()) - { - String queryString = req.getQueryString(); - logger.debug("Setting up guest access to URL: " + req.getRequestURI() + - ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : "")); - } - - DownloadContentWork dcw = new DownloadContentWork(req, res); - AuthenticationUtil.runAs(dcw, AuthenticationUtil.getGuestUserName()); - } - - /** - * Helper to generate a URL to a content node for downloading content from the server. - * The content is supplied as an HTTP1.1 attachment to the response. This generally means - * a browser should prompt the user to save the content to specified location. - * - * @param ref NodeRef of the content node to generate URL for (cannot be null) - * @param name File name to return in the URL (cannot be null) - * - * @return URL to download the content from the specified node - */ - public final static String generateDownloadURL(NodeRef ref, String name) - { - return generateUrl(DOWNLOAD_URL, ref, name); - } - - /** - * Helper to generate a URL to a content node for downloading content from the server. - * The content is supplied directly in the reponse. This generally means a browser will - * attempt to open the content directly if possible, else it will prompt to save the file. - * - * @param ref NodeRef of the content node to generate URL for (cannot be null) - * @param name File name to return in the URL (cannot be null) - * - * @return URL to download the content from the specified node - */ - public final static String generateBrowserURL(NodeRef ref, String name) - { - return generateUrl(BROWSER_URL, ref, name); - } - - /** - * Class to wrap the call to processDownloadRequest. - * - * @author gavinc - */ - public class DownloadContentWork implements RunAsWork - { - private HttpServletRequest req = null; - private HttpServletResponse res = null; - - public DownloadContentWork(HttpServletRequest req, HttpServletResponse res) - { - this.req = req; - this.res = res; - } - - public Object doWork() throws Exception - { - processDownloadRequest(this.req, this.res, false, true); - - return null; - } - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/GuestTemplateContentServlet.java b/war/src/main/java/org/alfresco/web/app/servlet/GuestTemplateContentServlet.java deleted file mode 100644 index d69268864c..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/GuestTemplateContentServlet.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; -import java.text.MessageFormat; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.security.AuthenticationService; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.cmr.security.PersonService; -import org.alfresco.web.bean.repository.User; -import org.alfresco.web.ui.repo.component.template.DefaultModelHelper; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Servlet responsible for streaming content from a template processed against a node directly - * to the response stream. - *

- * The URL to the servlet should be generated thus: - *

/alfresco/template/workspace/SpacesStore/0000-0000-0000-0000
- * or - *
/alfresco/template/workspace/SpacesStore/0000-0000-0000-0000/workspace/SpacesStore/0000-0000-0000-0000
- * or - *
/alfresco/template?templatePath=/Company%20Home/Data%20Dictionary/Presentation%20Templates/doc_info.ftl&contextPath=/Company%20Home/mydoc.txt
- *

- * The store protocol, followed by the store ID, followed by the content Node Id used to - * identify the node to execute the default template for. The second set of elements encode - * the store and node Id of the template to used if a default is not set or not requested. Instead - * of using NodeRef references to the template and context, path arguments can be used. The URL args - * of 'templatePath' and 'contextPath' can be used instead to specify name based encoded Paths to the - * template and its context. - *

- * The URL may be followed by a 'mimetype' argument specifying the mimetype to return the result as - * on the stream. Otherwise it is assumed that HTML is the default response mimetype. - *

- * Like most Alfresco servlets, the URL may be followed by a valid 'ticket' argument for authentication: - * ?ticket=1234567890 - *

- * And/or also followed by the "?guest=true" argument to force guest access login for the URL. If the - * guest=true parameter is used the current session will be logged out and the guest user logged in. - * Therefore upon completion of this request the current user will be "guest". - *

- * This servlet only accesses content available to the guest user. If the guest user does not - * have access to the requested a 401 Forbidden response is returned to the caller. - *

- * This servlet does not effect the current session, therefore if guest access is required to a - * resource this servlet can be used without logging out the current user. - * - * @author gavinc - * @deprecated 5.0 not exposed in web-client web.xml - */ -public class GuestTemplateContentServlet extends BaseTemplateContentServlet -{ - private static final long serialVersionUID = -2510767849932627519L; - - private static final Log logger = LogFactory.getLog(GuestTemplateContentServlet.class); - - private static final String DEFAULT_URL = "/guestTemplate/{0}/{1}/{2}"; - private static final String TEMPLATE_URL = "/guestTemplate/{0}/{1}/{2}/{3}/{4}/{5}"; - - @Override - protected Log getLogger() - { - return logger; - } - - @Override - protected Map buildModel(ServiceRegistry services, HttpServletRequest req, - NodeRef templateRef) - { - // setup the guest user to pass to the build model helper method - AuthenticationService auth = (AuthenticationService)services.getAuthenticationService(); - PersonService personService = (PersonService)services.getPersonService(); - NodeService nodeService = (NodeService)services.getNodeService(); - - NodeRef guestRef = personService.getPerson(AuthenticationUtil.getGuestUserName()); - User guestUser = new User(AuthenticationUtil.getGuestUserName(), auth.getCurrentTicket(), guestRef); - NodeRef guestHomeRef = (NodeRef)nodeService.getProperty(guestRef, ContentModel.PROP_HOMEFOLDER); - if (nodeService.exists(guestHomeRef) == false) - { - throw new InvalidNodeRefException(guestHomeRef); - } - guestUser.setHomeSpaceId(guestHomeRef.getId()); - - // build the default model - return DefaultModelHelper.buildDefaultModel(services, guestUser, templateRef, this.imageResolver); - } - - /** - * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - protected void service(HttpServletRequest req, HttpServletResponse res) - throws ServletException, IOException - { - if (logger.isDebugEnabled()) - { - String queryString = req.getQueryString(); - logger.debug("Setting up guest access to URL: " + req.getRequestURI() + - ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : "")); - } - - TemplateContentWork tcw = new TemplateContentWork(req, res); - AuthenticationUtil.runAs(tcw, AuthenticationUtil.getGuestUserName()); - } - - /** - * Helper to generate a URL to process a template against a node. - *

- * The result of the template is supplied returned as the response. - * - * @param nodeRef NodeRef of the content node to generate URL for (cannot be null) - * @param templateRef NodeRef of the template to process against, or null to use default - * - * @return URL to process the template - */ - public final static String generateURL(NodeRef nodeRef, NodeRef templateRef) - { - if (templateRef == null) - { - return MessageFormat.format(DEFAULT_URL, new Object[] { - nodeRef.getStoreRef().getProtocol(), - nodeRef.getStoreRef().getIdentifier(), - nodeRef.getId() } ); - } - else - { - return MessageFormat.format(TEMPLATE_URL, new Object[] { - nodeRef.getStoreRef().getProtocol(), - nodeRef.getStoreRef().getIdentifier(), - nodeRef.getId(), - templateRef.getStoreRef().getProtocol(), - templateRef.getStoreRef().getIdentifier(), - templateRef.getId()} ); - } - } - - /** - * Class to wrap the call to processTemplateRequest. - * - * @author gavinc - */ - public class TemplateContentWork implements RunAsWork - { - private HttpServletRequest req = null; - private HttpServletResponse res = null; - - public TemplateContentWork(HttpServletRequest req, HttpServletResponse res) - { - this.req = req; - this.res = res; - } - - public Object doWork() throws Exception - { - processTemplateRequest(this.req, this.res, false); - - return null; - } - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/HTTPRequestAuthenticationFilter.java b/war/src/main/java/org/alfresco/web/app/servlet/HTTPRequestAuthenticationFilter.java deleted file mode 100644 index bec80f5c45..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/HTTPRequestAuthenticationFilter.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.repo.security.authentication.AuthenticationComponent; -import org.alfresco.repo.security.authentication.AuthenticationException; -import org.alfresco.service.cmr.security.AuthenticationService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.User; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.WebApplicationContextUtils; - -/** - * Generic HTTP request filter for setting the authenticated user when used with authentication systems such as - * SiteMinder, Novell IChains and CAS. - * - * @author Andy Hind - */ -public class HTTPRequestAuthenticationFilter implements Filter -{ - private static Log logger = LogFactory.getLog(HTTPRequestAuthenticationFilter.class); - - private ServletContext context; - - private String loginPage; - - private AuthenticationComponent authComponent; - - private AuthenticationService authenticationService; - - private String httpServletRequestAuthHeaderName; - - // By default match everything if this is not set - private String authPatternString = null; - - private Pattern authPattern = null; - - public void destroy() - { - // Nothing to do - } - - /** - * Run the filter - * - * @param sreq - * ServletRequest - * @param sresp - * ServletResponse - * @param chain - * FilterChain - * @exception IOException - * @exception ServletException - */ - public void doFilter(ServletRequest sreq, ServletResponse sresp, FilterChain chain) throws IOException, - ServletException - { - // Get the HTTP request/response/session - - HttpServletRequest req = (HttpServletRequest) sreq; - HttpServletResponse resp = (HttpServletResponse) sresp; - - // Check for the auth header - - String authHdr = req.getHeader(httpServletRequestAuthHeaderName); - if (logger.isDebugEnabled()) - { - if (authHdr == null) - { - logger.debug("Header not found: " + httpServletRequestAuthHeaderName); - } - else - { - logger.debug("Header is <" + authHdr + ">"); - } - } - - // Throw an error if we have an unknown authentication - - if ((authHdr == null) || (authHdr.length() < 1)) - { - resp.sendRedirect(req.getContextPath() + "/jsp/noaccess.jsp"); - return; - } - - // Get the user - - String userName = ""; - if (authPattern != null) - { - Matcher matcher = authPattern.matcher(authHdr); - if (matcher.matches()) - { - userName = matcher.group(); - if ((userName == null) || (userName.length() < 1)) - { - if (logger.isDebugEnabled()) - { - logger.debug("Extracted null or empty user name from pattern " - + authPatternString + " against " + authHdr); - } - resp.sendRedirect(req.getContextPath() + "/jsp/noaccess.jsp"); - return; - } - } - else - { - if (logger.isDebugEnabled()) - { - logger.debug("no pattern match for " + authPatternString + " against " + authHdr); - } - resp.sendRedirect(req.getContextPath() + "/jsp/noaccess.jsp"); - return; - } - } - else - { - userName = authHdr; - } - - if (logger.isDebugEnabled()) - { - logger.debug("User = " + userName); - } - - // See if there is a user in the session and test if it matches - - User user = AuthenticationHelper.getUser(this.context, req, resp); - - if (user != null) - { - try - { - // Debug - - if (logger.isDebugEnabled()) - logger.debug("User " + user.getUserName() + " validate ticket"); - - // Validate the user ticket - - if (user.getUserName().equals(userName)) - { - - // Set the current locale - authComponent.clearCurrentSecurityContext(); - authComponent.setCurrentUser(user.getUserName()); - AuthenticationHelper.setupThread(this.context, req, resp, true); - chain.doFilter(sreq, sresp); - return; - } - else - { - // No match - setAuthenticatedUser(req, resp, userName); - } - } - catch (AuthenticationException ex) - { - if (logger.isErrorEnabled()) - logger.error("Failed to validate user " + user.getUserName(), ex); - } - } - - setAuthenticatedUser(req, resp, userName); - - // Redirect the login page as it is never seen as we always login by name - if (req.getRequestURI().endsWith(getLoginPage()) == true) - { - if (logger.isDebugEnabled()) - logger.debug("Login page requested, chaining ..."); - - resp.sendRedirect(req.getContextPath() + BaseServlet.FACES_SERVLET + FacesHelper.BROWSE_VIEW_ID); - return; - } - else - { - chain.doFilter(sreq, sresp); - return; - } - } - - /** - * Set the authenticated user. It does not check that the user exists at the moment. - * - * @param req - * the request - * @param res - * the response - * @param userName - * the user name - */ - private void setAuthenticatedUser(HttpServletRequest req, HttpServletResponse res, - String userName) - { - // Set the authentication - authComponent.clearCurrentSecurityContext(); - authComponent.setCurrentUser(userName); - - // Set up the user information - AuthenticationHelper.setUser(context, req, userName, authenticationService.getCurrentTicket(), true); - - // Set the locale using the session - AuthenticationHelper.setupThread(this.context, req, res, true); - } - - - public void init(FilterConfig config) throws ServletException - { - // Save the context - - this.context = config.getServletContext(); - - // Setup the authentication context - - WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context); - authComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent"); - authenticationService = (AuthenticationService) ctx.getBean("AuthenticationService"); - - httpServletRequestAuthHeaderName = config.getInitParameter("httpServletRequestAuthHeaderName"); - if(httpServletRequestAuthHeaderName == null) - { - httpServletRequestAuthHeaderName = "x-user"; - } - this.authPatternString = config.getInitParameter("authPatternString"); - if (this.authPatternString != null) - { - try - { - authPattern = Pattern.compile(this.authPatternString); - } - catch (PatternSyntaxException e) - { - logger.warn("Invalid pattern: " + this.authPatternString, e); - authPattern = null; - } - } - - } - - /** - * Return the login page address - * - * @return String - */ - private String getLoginPage() - { - if (loginPage == null) - { - loginPage = Application.getLoginPage(context); - } - - return loginPage; - } - -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/KerberosAuthenticationFilter.java b/war/src/main/java/org/alfresco/web/app/servlet/KerberosAuthenticationFilter.java deleted file mode 100644 index a0d9c0b28f..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/KerberosAuthenticationFilter.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.alfresco.repo.SessionUser; -import org.alfresco.repo.web.auth.WebCredentials; -import org.alfresco.repo.webdav.auth.BaseKerberosAuthenticationFilter; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.bean.repository.User; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Kerberos Authentication Filter Class - * - * @author GKSpencer - */ -public class KerberosAuthenticationFilter extends BaseKerberosAuthenticationFilter -{ - // Debug logging - - private static Log logger = LogFactory.getLog(KerberosAuthenticationFilter.class); - - - /* (non-Javadoc) - * @see org.alfresco.repo.webdav.auth.BaseKerberosAuthenticationFilter#init() - */ - @Override - protected void init() throws ServletException - { - // Call the base Kerberos filter initialization - super.init(); - - // Use the web client user attribute name - setUserAttributeName(AuthenticationHelper.AUTHENTICATION_USER); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.webdav.auth.BaseAuthenticationFilter#createUserObject(java.lang.String, java.lang.String, org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.cmr.repository.NodeRef) - */ - @Override - protected SessionUser createUserObject(String userName, String ticket, NodeRef personNode, NodeRef homeSpaceRef) - { - // Create a web client user object - User user = new User(userName, ticket, personNode); - user.setHomeSpaceId(homeSpaceRef.getId()); - - return user; - } - - /* - * (non-Javadoc) - * @see org.alfresco.repo.webdav.auth.BaseSSOAuthenticationFilter#onValidate(javax.servlet.ServletContext, - * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - protected void onValidate(ServletContext sc, HttpServletRequest req, HttpServletResponse res, WebCredentials credentials) - { - super.onValidate(sc, req, res, credentials); - - // Set the locale using the session - AuthenticationHelper.setupThread(sc, req, res, !req.getServletPath().equals("/wcs") && !req.getServletPath().equals("/wcservice")); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.webdav.auth.BaseSSOAuthenticationFilter#onValidateFailed(javax.servlet.ServletContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, javax.servlet.http.HttpSession) - */ - @Override - protected void onValidateFailed(ServletContext sc, HttpServletRequest req, HttpServletResponse res, HttpSession session, WebCredentials credentials) - throws IOException - { - super.onValidateFailed(sc, req, res, session, credentials); - - // Redirect to the login page if user validation fails - redirectToLoginPage(req, res); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.webdav.auth.BaseNTLMAuthenticationFilter#onLoginComplete(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - protected boolean onLoginComplete(ServletContext sc, HttpServletRequest req, HttpServletResponse res, boolean userInit) - throws IOException - { - String requestURI = req.getRequestURI(); - return true; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.webdav.auth.BaseSSOAuthenticationFilter#writeLoginPageLink(javax.servlet.ServletContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - protected void writeLoginPageLink(ServletContext context, HttpServletRequest req, HttpServletResponse resp) - throws IOException - { - BaseServlet.redirectToLoginPage(req, resp, context, false); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.webdav.auth.BaseNTLMAuthenticationFilter#getLogger() - */ - @Override - final protected Log getLogger() - { - return logger; - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/ModeDetectionFilter.java b/war/src/main/java/org/alfresco/web/app/servlet/ModeDetectionFilter.java deleted file mode 100644 index 6513c152ea..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/ModeDetectionFilter.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - -import org.alfresco.web.app.Application; - - -/** - * Filter that determines whether the application is running inside a portal - * server or servlet engine. The fact that this filter gets called means - * the application is running inside a servlet engine. - * - * @author gavinc - * @deprecated 5.0 not exposed in web-client web.xml - */ -public class ModeDetectionFilter implements Filter -{ - /** - * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) - */ - public void init(FilterConfig config) throws ServletException - { - // nothing to do - } - - /** - * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) - */ - public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) - throws IOException, ServletException - { - // as we get here means we are inside a servlet engine as portal servers - // do not support the calling of filters yet - Application.setInPortalServer(false); - - // continue filter chaining - chain.doFilter(req, res); - } - - /** - * @see javax.servlet.Filter#destroy() - */ - public void destroy() - { - // nothing to do - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/NTLMAuthenticationFilter.java b/war/src/main/java/org/alfresco/web/app/servlet/NTLMAuthenticationFilter.java deleted file mode 100644 index fc7f57a7f9..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/NTLMAuthenticationFilter.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.alfresco.repo.SessionUser; -import org.alfresco.repo.web.auth.WebCredentials; -import org.alfresco.repo.webdav.auth.BaseNTLMAuthenticationFilter; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.bean.repository.User; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Web-client NTLM Authentication Filter Class - * - * @author GKSpencer - */ -public class NTLMAuthenticationFilter extends BaseNTLMAuthenticationFilter -{ - // Debug logging - private static Log logger = LogFactory.getLog(NTLMAuthenticationFilter.class); - - - /* (non-Javadoc) - * @see org.alfresco.repo.webdav.auth.BaseNTLMAuthenticationFilter#init() - */ - @Override - protected void init() throws ServletException - { - // Call the base NTLM filter initialization - super.init(); - - // Use the web client user attribute name - setUserAttributeName(AuthenticationHelper.AUTHENTICATION_USER); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.webdav.auth.BaseAuthenticationFilter#createUserObject(java.lang.String, java.lang.String, org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.cmr.repository.NodeRef) - */ - @Override - protected SessionUser createUserObject(String userName, String ticket, NodeRef personNode, NodeRef homeSpaceRef) - { - // Create a web client user object - User user = new User( userName, ticket, personNode); - user.setHomeSpaceId( homeSpaceRef.getId()); - - return user; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.webdav.auth.BaseSSOAuthenticationFilter#onValidate(javax.servlet.ServletContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - protected void onValidate(ServletContext sc, HttpServletRequest req, HttpServletResponse res, WebCredentials credentials) - { - super.onValidate(sc, req, res, credentials); - - // Set the locale using the session - AuthenticationHelper.setupThread(sc, req, res, !req.getServletPath().equals("/wcs") && !req.getServletPath().equals("/wcservice")); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.webdav.auth.BaseSSOAuthenticationFilter#onValidateFailed(javax.servlet.ServletContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, javax.servlet.http.HttpSession) - */ - @Override - protected void onValidateFailed(ServletContext sc, HttpServletRequest req, HttpServletResponse res, HttpSession session, WebCredentials credentials) - throws IOException - { - super.onValidateFailed(sc, req, res, session, credentials); - - // Redirect to the login page if user validation fails - redirectToLoginPage(req, res); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.webdav.auth.BaseNTLMAuthenticationFilter#onLoginComplete(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - protected boolean onLoginComplete(ServletContext sc, HttpServletRequest req, HttpServletResponse res, boolean userInit) - throws IOException - { - String requestURI = req.getRequestURI(); - return true; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.webdav.auth.BaseSSOAuthenticationFilter#writeLoginPageLink(javax.servlet.ServletContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - protected void writeLoginPageLink(ServletContext context, HttpServletRequest req, HttpServletResponse resp) - throws IOException - { - BaseServlet.redirectToLoginPage(req, resp, context, false); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.webdav.auth.BaseNTLMAuthenticationFilter#getLogger() - */ - @Override - final protected Log getLogger() - { - return logger; - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/SecurityContextCleanupPhaseListener.java b/war/src/main/java/org/alfresco/web/app/servlet/SecurityContextCleanupPhaseListener.java deleted file mode 100644 index 82ec1d07cc..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/SecurityContextCleanupPhaseListener.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import javax.faces.event.PhaseEvent; -import javax.faces.event.PhaseId; -import javax.faces.event.PhaseListener; - -import net.sf.acegisecurity.context.ContextHolder; - -/** - * This JSF phase listener clears security context after finishing rendering of each request to back-end bean. This action is required due to conflict in HTTP request processing - * threads in application server thread pool. Not cleaned up security context becomes shared between Alfresco Explorer and CMIS.
- *
- * See "cmisatom URL (opencmis backed by Apache Chemistry OpenCMIS) does not support External authentication" and - * "Security context for Alfresco Explorer is not being cleaned up after processing a request" for more details - * - * @since 4.1.4 - * @author Dmitry Velichkevich - */ -public class SecurityContextCleanupPhaseListener implements PhaseListener -{ - private static final long serialVersionUID = 1L; - - public SecurityContextCleanupPhaseListener() - { - } - - @Override - public void afterPhase(PhaseEvent phaseevent) - { - ContextHolder.setContext(null); - } - - @Override - public void beforePhase(PhaseEvent phaseevent) - { - } - - @Override - public PhaseId getPhaseId() - { - return PhaseId.RENDER_RESPONSE; - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/TemplateContentServlet.java b/war/src/main/java/org/alfresco/web/app/servlet/TemplateContentServlet.java deleted file mode 100644 index 339b64f4ac..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/TemplateContentServlet.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; -import java.text.MessageFormat; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.app.Application; -import org.alfresco.web.ui.repo.component.template.DefaultModelHelper; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Servlet responsible for streaming content from a template processed against a node directly - * to the response stream. - *

- * The URL to the servlet should be generated thus: - *

/alfresco/template/workspace/SpacesStore/0000-0000-0000-0000
- * or - *
/alfresco/template/workspace/SpacesStore/0000-0000-0000-0000/workspace/SpacesStore/0000-0000-0000-0000
- * or - *
/alfresco/template?templatePath=/Company%20Home/Data%20Dictionary/Presentation%20Templates/doc_info.ftl&contextPath=/Company%20Home/mydoc.txt
- *

- * The store protocol, followed by the store ID, followed by the content Node Id used to - * identify the node to execute the default template for. The second set of elements encode - * the store and node Id of the template to used if a default is not set or not requested. Instead - * of using NodeRef references to the template and context, path arguments can be used. The URL args - * of 'templatePath' and 'contextPath' can be used instead to specify name based encoded Paths to the - * template and its context. - *

- * The URL may be followed by a 'mimetype' argument specifying the mimetype to return the result as - * on the stream. Otherwise it is assumed that HTML is the default response mimetype. - *

- * Like most Alfresco servlets, the URL may be followed by a valid 'ticket' argument for authentication: - * ?ticket=1234567890 - *

- * And/or also followed by the "?guest=true" argument to force guest access login for the URL. If the - * guest=true parameter is used the current session will be logged out and the guest user logged in. - * Therefore upon completion of this request the current user will be "guest". - *

- * If the user attempting the request is not authorised to access the requested node the login page - * will be redirected to. - * - * @author Kevin Roast - * @deprecated 5.0 not exposed in web-client web.xml - */ -public class TemplateContentServlet extends BaseTemplateContentServlet -{ - private static final long serialVersionUID = -2510767849932627519L; - - private static final Log logger = LogFactory.getLog(TemplateContentServlet.class); - - private static final String DEFAULT_URL = "/t/{0}/{1}/{2}"; - private static final String TEMPLATE_URL = "/t/{0}/{1}/{2}/{3}/{4}/{5}"; - - @Override - protected Log getLogger() - { - return logger; - } - - @Override - protected Map buildModel(ServiceRegistry services, HttpServletRequest req, - NodeRef templateRef) - { - return DefaultModelHelper.buildDefaultModel(services, - Application.getCurrentUser(req.getSession()), templateRef, this.imageResolver); - } - - /** - * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - protected void service(HttpServletRequest req, HttpServletResponse res) - throws ServletException, IOException - { - if (logger.isDebugEnabled()) - { - String queryString = req.getQueryString(); - logger.debug("Authenticating request to URL: " + req.getRequestURI() + - ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : "")); - } - - AuthenticationStatus status = servletAuthenticate(req, res); - if (status == AuthenticationStatus.Failure) - { - return; - } - - setNoCacheHeaders(res); - - processTemplateRequest(req, res, true); - } - - /** - * Helper to generate a URL to process a template against a node. - *

- * The result of the template is supplied returned as the response. - * - * @param nodeRef NodeRef of the content node to generate URL for (cannot be null) - * @param templateRef NodeRef of the template to process against, or null to use default - * - * @return URL to process the template - */ - public final static String generateURL(NodeRef nodeRef, NodeRef templateRef) - { - if (templateRef == null) - { - return MessageFormat.format(DEFAULT_URL, new Object[] { - nodeRef.getStoreRef().getProtocol(), - nodeRef.getStoreRef().getIdentifier(), - nodeRef.getId() } ); - } - else - { - return MessageFormat.format(TEMPLATE_URL, new Object[] { - nodeRef.getStoreRef().getProtocol(), - nodeRef.getStoreRef().getIdentifier(), - nodeRef.getId(), - templateRef.getStoreRef().getProtocol(), - templateRef.getStoreRef().getIdentifier(), - templateRef.getId()} ); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/UploadContentServlet.java b/war/src/main/java/org/alfresco/web/app/servlet/UploadContentServlet.java deleted file mode 100644 index 7a10722c31..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/UploadContentServlet.java +++ /dev/null @@ -1,284 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; -import java.util.Locale; -import java.util.StringTokenizer; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.content.encoding.ContentCharsetFinder; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.ContentData; -import org.alfresco.service.cmr.repository.ContentService; -import org.alfresco.service.cmr.repository.ContentWriter; -import org.alfresco.service.cmr.repository.MimetypeService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.repository.StoreRef; -import org.alfresco.service.cmr.security.AccessStatus; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.namespace.QName; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.extensions.surf.util.I18NUtil; - -/** - * Servlet responsible for streaming content directly into the repository from the PUT request. - * The appropriate mimetype is calculated based on filename extension. - *

- * The URL to the servlet should be generated thus: - *

/alfresco/upload/workspace/SpacesStore/0000-0000-0000-0000/myfile.pdf
- * or - *
/alfresco/upload/myfile.pdf
- *

- * If the store and node id are specified in the URL then the content provided will be streamed onto the node - * using an updating writer, updating the content property value accordingly. - *

- * If only the file name is specified the content will be streamed into the content store and the content data - * will be returned in the reposonse. This can then be used to update the value of a content property manually. - * Any used content will be cleared up in the usual manner. - *

- * By default, the download assumes that the content is on the - * {@link org.alfresco.model.ContentModel#PROP_CONTENT content property}.
- * To set the content of a specific model property, use a 'property' arg, providing the qualified name of the property. - *

- * Like most Alfresco servlets, the URL may be followed by a valid 'ticket' argument for authentication: - * ?ticket=1234567890 - *

- * Guest access is currently disabled for this servlet. - * - * @author Roy Wetherall - */ -public class UploadContentServlet extends BaseServlet -{ - /** Serial version UID */ - private static final long serialVersionUID = 1055960980867420355L; - - /** Logger */ - private static Log logger = LogFactory.getLog(UploadContentServlet.class); - - /** Default mime type */ - protected static final String MIMETYPE_OCTET_STREAM = "application/octet-stream"; - - /** Argument properties */ - protected static final String ARG_PROPERTY = "property"; - protected static final String ARG_MIMETYPE = "mimetype"; - protected static final String ARG_ENCODING = "encoding"; - protected static final String ARG_LOCALE = "locale"; - - /** - * @see javax.servlet.http.HttpServlet#doPut(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException - { - if (logger.isDebugEnabled() == true) - { - String queryString = req.getQueryString(); - logger.debug("Authenticating request to URL: " + req.getRequestURI() - + ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : "")); - } - - AuthenticationStatus status = servletAuthenticate(req, res, false); - if (status == AuthenticationStatus.Failure || status == AuthenticationStatus.Guest) - { - res.sendError(HttpServletResponse.SC_UNAUTHORIZED); - return; - } - - // Tokenise the URI - String uri = req.getRequestURI(); - uri = uri.substring(req.getContextPath().length()); - StringTokenizer t = new StringTokenizer(uri, "/"); - int tokenCount = t.countTokens(); - - t.nextToken(); // skip servlet name - - // get or calculate the noderef and filename to download as - NodeRef nodeRef = null; - String filename = null; - QName propertyQName = null; - - if (tokenCount == 2) - { - // filename is the only token - filename = t.nextToken(); - } - else if (tokenCount == 4 || tokenCount == 5) - { - // assume 'workspace' or other NodeRef based protocol for remaining URL - // elements - StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken()); - String id = t.nextToken(); - // build noderef from the appropriate URL elements - nodeRef = new NodeRef(storeRef, id); - - if (tokenCount == 5) - { - // filename is last remaining token - filename = t.nextToken(); - } - - // get qualified of the property to get content from - default to - // ContentModel.PROP_CONTENT - propertyQName = ContentModel.PROP_CONTENT; - String property = req.getParameter(ARG_PROPERTY); - if (property != null && property.length() != 0) - { - propertyQName = QName.createQName(property); - } - } - else - { - logger.debug("Upload URL did not contain all required args: " + uri); - res.sendError(HttpServletResponse.SC_EXPECTATION_FAILED); - return; - } - - // get the services we need to retrieve the content - ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext()); - ContentService contentService = serviceRegistry.getContentService(); - PermissionService permissionService = serviceRegistry.getPermissionService(); - MimetypeService mimetypeService = serviceRegistry.getMimetypeService(); - NodeService nodeService = serviceRegistry.getNodeService(); - - InputStream is = req.getInputStream(); - BufferedInputStream inputStream = new BufferedInputStream(is); - - // Sort out the mimetype - String mimetype = req.getParameter(ARG_MIMETYPE); - if (mimetype == null || mimetype.length() == 0) - { - mimetype = MIMETYPE_OCTET_STREAM; - if (filename != null) - { - MimetypeService mimetypeMap = serviceRegistry.getMimetypeService(); - int extIndex = filename.lastIndexOf('.'); - if (extIndex != -1) - { - String ext = filename.substring(extIndex + 1); - mimetype = mimetypeService.getMimetype(ext); - } - } - } - - // Get the encoding - String encoding = req.getParameter(ARG_ENCODING); - if (encoding == null || encoding.length() == 0) - { - // Get the encoding - ContentCharsetFinder charsetFinder = mimetypeService.getContentCharsetFinder(); - Charset charset = charsetFinder.getCharset(inputStream, mimetype); - encoding = charset.name(); - } - - // Get the locale - Locale locale = I18NUtil.parseLocale(req.getParameter(ARG_LOCALE)); - if (locale == null) - { - locale = I18NUtil.getContentLocale(); - if (nodeRef != null) - { - ContentData contentData = (ContentData) nodeService.getProperty(nodeRef, propertyQName); - if (contentData != null) - { - locale = contentData.getLocale(); - } - } - } - - if (logger.isDebugEnabled()) - { - if (nodeRef != null) {logger.debug("Found NodeRef: " + nodeRef.toString());} - logger.debug("For property: " + propertyQName); - logger.debug("File name: " + filename); - logger.debug("Mimetype: " + mimetype); - logger.debug("Encoding: " + encoding); - logger.debug("Locale: " + locale); - } - - // Check that the user has the permissions to write the content - if (permissionService.hasPermission(nodeRef, PermissionService.WRITE_CONTENT) == AccessStatus.DENIED) - { - if (logger.isDebugEnabled() == true) - { - logger.debug("User does not have permissions to wrtie content for NodeRef: " + nodeRef.toString()); - } - - if (logger.isDebugEnabled()) - { - logger.debug("Returning 403 Forbidden error..."); - } - - res.sendError(HttpServletResponse.SC_FORBIDDEN); - return; - } - - // Try and get the content writer - ContentWriter writer = contentService.getWriter(nodeRef, propertyQName, true); - if (writer == null) - { - if (logger.isDebugEnabled() == true) - { - logger.debug("Content writer cannot be obtained for NodeRef: " + nodeRef.toString()); - } - res.sendError(HttpServletResponse.SC_EXPECTATION_FAILED); - return; - } - - // Set the mimetype, encoding and locale - writer.setMimetype(mimetype); - writer.setEncoding(encoding); - if (locale != null) - { - writer.setLocale(locale); - } - - // Stream the content into the repository - writer.putContent(inputStream); - - if (logger.isDebugEnabled() == true) - { - logger.debug("Content details: " + writer.getContentData().toString()); - } - - // Set return status - res.getWriter().write(writer.getContentData().toString()); - res.flushBuffer(); - - if (logger.isDebugEnabled() == true) - { - logger.debug("UploadContentServlet done"); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/UploadFileServlet.java b/war/src/main/java/org/alfresco/web/app/servlet/UploadFileServlet.java deleted file mode 100644 index b380bf27dd..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/UploadFileServlet.java +++ /dev/null @@ -1,286 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.util.TempFileProvider; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.ErrorBean; -import org.alfresco.web.bean.FileUploadBean; -import org.alfresco.web.config.ClientConfigElement; -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.RequestContext; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; -import org.apache.commons.fileupload.servlet.ServletFileUpload; -import org.apache.commons.fileupload.servlet.ServletRequestContext; -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONException; -import org.json.JSONObject; -import org.springframework.extensions.config.ConfigService; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.WebApplicationContextUtils; - -/** - * Servlet that takes a file uploaded via a browser and represents it as an - * UploadFileBean in the session - * - * @author gavinc - * @deprecated 5.0 not exposed in web-client web.xml - */ -public class UploadFileServlet extends BaseServlet -{ - private static final long serialVersionUID = -5482538466491052875L; - private static final Log logger = LogFactory.getLog(UploadFileServlet.class); - - private ConfigService configService; - - - /** - * @see javax.servlet.GenericServlet#init() - */ - @Override - public void init(ServletConfig sc) throws ServletException - { - super.init(sc); - - WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(sc.getServletContext()); - this.configService = (ConfigService)ctx.getBean("webClientConfigService"); - } - - /** - * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @SuppressWarnings("unchecked") - protected void service(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException - { - String uploadId = null; - String returnPage = null; - final RequestContext requestContext = new ServletRequestContext(request); - boolean isMultipart = ServletFileUpload.isMultipartContent(requestContext); - - try - { - AuthenticationStatus status = servletAuthenticate(request, response); - if (status == AuthenticationStatus.Failure) - { - return; - } - - if (!isMultipart) - { - throw new AlfrescoRuntimeException("This servlet can only be used to handle file upload requests, make" + - "sure you have set the enctype attribute on your form to multipart/form-data"); - } - - if (logger.isDebugEnabled()) - logger.debug("Uploading servlet servicing..."); - - FacesContext context = FacesContext.getCurrentInstance(); - Map session = context.getExternalContext().getSessionMap(); - ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); - - // ensure that the encoding is handled correctly - upload.setHeaderEncoding("UTF-8"); - - List fileItems = upload.parseRequest(request); - - FileUploadBean bean = new FileUploadBean(); - for (FileItem item : fileItems) - { - if(item.isFormField()) - { - if (item.getFieldName().equalsIgnoreCase("return-page")) - { - returnPage = item.getString(); - } - else if (item.getFieldName().equalsIgnoreCase("upload-id")) - { - uploadId = item.getString(); - } - } - else - { - String filename = item.getName(); - if (filename != null && filename.length() != 0) - { - if (logger.isDebugEnabled()) - { - logger.debug("Processing uploaded file: " + filename); - } - - // ADB-41: Ignore non-existent files i.e. 0 byte streams. - if (allowZeroByteFiles() == true || item.getSize() > 0) - { - // workaround a bug in IE where the full path is returned - // IE is only available for Windows so only check for the Windows path separator - filename = FilenameUtils.getName(filename); - final File tempFile = TempFileProvider.createTempFile("alfresco", ".upload"); - item.write(tempFile); - bean.setFile(tempFile); - bean.setFileName(filename); - bean.setFilePath(tempFile.getAbsolutePath()); - if (logger.isDebugEnabled()) - { - logger.debug("Temp file: " + tempFile.getAbsolutePath() + - " size " + tempFile.length() + - " bytes created from upload filename: " + filename); - } - } - else - { - if (logger.isWarnEnabled()) - logger.warn("Ignored file '" + filename + "' as there was no content, this is either " + - "caused by uploading an empty file or a file path that does not exist on the client."); - } - } - } - } - - session.put(FileUploadBean.getKey(uploadId), bean); - - if (bean.getFile() == null && uploadId != null && logger.isWarnEnabled()) - { - logger.warn("no file uploaded for upload id: " + uploadId); - } - - if (returnPage == null || returnPage.length() == 0) - { - throw new AlfrescoRuntimeException("return-page parameter has not been supplied"); - } - - JSONObject json; - try - { - json = new JSONObject(returnPage); - - if (json.has("id") && json.has("args")) - { - // finally redirect - if (logger.isDebugEnabled()) - { - logger.debug("Sending back javascript response " + returnPage); - } - response.setContentType(MimetypeMap.MIMETYPE_HTML); - response.setCharacterEncoding("utf-8"); - // work-around for WebKit protection against embedded javascript on POST body response - response.setHeader("X-XSS-Protection", "0"); - final PrintWriter out = response.getWriter(); - out.println(""); - out.close(); - } - } - catch (JSONException e) - { - // finally redirect - if (logger.isDebugEnabled()) - logger.debug("redirecting to: " + returnPage); - - response.sendRedirect(returnPage); - } - - if (logger.isDebugEnabled()) - logger.debug("upload complete"); - } - catch (Throwable error) - { - handleUploadException(request, response, error, returnPage); - } - } - - private void handleUploadException(HttpServletRequest request, HttpServletResponse response, Throwable error, String returnPage) - { - try - { - HttpSession session = request.getSession(true); - ErrorBean errorBean = (ErrorBean) session.getAttribute(ErrorBean.ERROR_BEAN_NAME); - if (errorBean == null) - { - errorBean = new ErrorBean(); - session.setAttribute(ErrorBean.ERROR_BEAN_NAME, errorBean); - } - errorBean.setLastError(error); - errorBean.setReturnPage(returnPage); - } - catch (Throwable e) - { - logger.error("Error while handling upload Exception", e); - } - try - { - String errorPage = Application.getErrorPage(getServletContext()); - - if (logger.isDebugEnabled()) - { - logger.debug("An error has occurred. Sending back response for redirecting to error page: " + errorPage); - } - - response.setContentType(MimetypeMap.MIMETYPE_HTML); - response.setCharacterEncoding("utf-8"); - final PrintWriter out = response.getWriter(); - out.println(" "); - out.close(); - } - catch (Exception e) - { - logger.error("Error while handling upload Exception", e); - } - } - - - private boolean allowZeroByteFiles() - { - ClientConfigElement clientConfig = (ClientConfigElement)configService.getGlobalConfig().getConfigElement( - ClientConfigElement.CONFIG_ELEMENT_ID); - return clientConfig.isZeroByteFileUploads(); - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/WebScriptSSOAuthenticationFilter.java b/war/src/main/java/org/alfresco/web/app/servlet/WebScriptSSOAuthenticationFilter.java deleted file mode 100644 index 9aca0463c5..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/WebScriptSSOAuthenticationFilter.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; - -import javax.servlet.FilterChain; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; - -import org.alfresco.repo.management.subsystems.ActivateableBean; -import org.alfresco.repo.web.filter.beans.DependencyInjectedFilter; -import org.alfresco.repo.webdav.auth.BaseAuthenticationFilter; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.extensions.surf.util.URLDecoder; -import org.springframework.extensions.webscripts.Description.RequiredAuthentication; -import org.springframework.extensions.webscripts.Match; -import org.springframework.extensions.webscripts.RuntimeContainer; - -/** - * WebScript aware Authentication Filter Class. Takes into account the authentication setting in the descriptor for the - * webscript before chaining to the downstream authentication filters. If authentication is not required then chains - * with the NO_AUTH_REQUIRED request attribute set, which should cause any downstream authentication filter to bypass - * authentication checks. - * - * @author Kevin Roast - * @author dward - */ -public class WebScriptSSOAuthenticationFilter extends BaseAuthenticationFilter implements DependencyInjectedFilter, - ActivateableBean -{ - private static final Log logger = LogFactory.getLog(WebScriptSSOAuthenticationFilter.class); - private RuntimeContainer container; - private boolean isActive = true; - - /** - * @param container the container to set - */ - public void setContainer(RuntimeContainer container) - { - this.container = container; - } - - /** - * Activates or deactivates the bean - * - * @param active - * true if the bean is active and initialization should complete - */ - public final void setActive(boolean active) - { - this.isActive = active; - } - - /* - * (non-Javadoc) - * @see org.alfresco.repo.management.subsystems.ActivateableBean#isActive() - */ - public final boolean isActive() - { - return isActive; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.webdav.auth.BaseNTLMAuthenticationFilter#doFilter(javax.servlet.ServletContext, javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) - */ - public void doFilter(ServletContext context, ServletRequest sreq, ServletResponse sresp, FilterChain chain) - throws IOException, ServletException - { - // Get the HTTP request/response - HttpServletRequest req = (HttpServletRequest)sreq; - - // find a webscript match for the requested URI - String requestURI = req.getRequestURI(); - String pathInfo = requestURI.substring((req.getContextPath() + req.getServletPath()).length()); - - if (getLogger().isDebugEnabled()) - getLogger().debug("Processing request: " + requestURI + " SID:" + - (req.getSession(false) != null ? req.getSession().getId() : null)); - - Match match = container.getRegistry().findWebScript(req.getMethod(), URLDecoder.decode(pathInfo)); - if (match != null && match.getWebScript() != null) - { - // check the authentication required - if none then we don't want any of - // the filters down the chain to require any authentication checks - if (RequiredAuthentication.none == match.getWebScript().getDescription().getRequiredAuthentication()) - { - if (getLogger().isDebugEnabled()) - getLogger().debug("Found webscript with no authentication - set NO_AUTH_REQUIRED flag."); - req.setAttribute(NO_AUTH_REQUIRED, Boolean.TRUE); - } - } - - chain.doFilter(sreq, sresp); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.webdav.auth.BaseAuthenticationFilter#getLogger() - */ - @Override - protected Log getLogger() - { - return logger; - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/WebscriptCookieAuthenticationFilter.java b/war/src/main/java/org/alfresco/web/app/servlet/WebscriptCookieAuthenticationFilter.java deleted file mode 100644 index f30e5e2828..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/WebscriptCookieAuthenticationFilter.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; - -import javax.servlet.FilterChain; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.repo.SessionUser; -import org.alfresco.repo.web.filter.beans.DependencyInjectedFilter; -import org.alfresco.repo.webdav.auth.BaseAuthenticationFilter; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.bean.repository.User; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - - -/** - * WebScript aware Authentication Filter. Directly handles login script calls, allowing Surf to establish a cookie - * for a manual login, rather than the usual stateless ticket based logins. - *

- * This functionality has been extracted from the WebScriptSSOAuthenticationFilter so that they can work independently. - * - * @author Gethin James - */ -public class WebscriptCookieAuthenticationFilter extends BaseAuthenticationFilter implements DependencyInjectedFilter -{ - private static final Log logger = LogFactory.getLog(WebscriptCookieAuthenticationFilter.class); - private static final String API_LOGIN = "/api/login"; - - public WebscriptCookieAuthenticationFilter() - { - setUserAttributeName(AuthenticationHelper.AUTHENTICATION_USER); - } - - - @Override - public void doFilter(ServletContext context, ServletRequest sreq, ServletResponse sresp, FilterChain chain) throws IOException, ServletException - { - // Get the HTTP request/response - HttpServletRequest req = (HttpServletRequest)sreq; - HttpServletResponse res = (HttpServletResponse)sresp; - - // Allow propagation of manual logins to the session user - if (API_LOGIN.equals(req.getPathInfo()) && req.getMethod().equalsIgnoreCase("POST")) - { - if (handleLoginForm(req, res)); - { - // Establish the session locale using request headers rather than web client preferences - AuthenticationHelper.setupThread(context, req, res, false); - } - } - else - { - chain.doFilter(sreq, sresp); - } - } - - @Override - protected SessionUser createUserObject(String userName, String ticket, NodeRef personNode, NodeRef homeSpaceRef) - { - // Create a web client user object - User user = new User( userName, ticket, personNode); - user.setHomeSpaceId( homeSpaceRef.getId()); - - return user; - } - - @Override - protected Log getLogger() - { - return logger; - } - -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/WorkflowDefinitionImageServlet.java b/war/src/main/java/org/alfresco/web/app/servlet/WorkflowDefinitionImageServlet.java deleted file mode 100644 index 503f1b5c2d..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/WorkflowDefinitionImageServlet.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.StringTokenizer; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.workflow.WorkflowException; -import org.alfresco.service.cmr.workflow.WorkflowService; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.WebApplicationContextUtils; - - -/** - * Render Workflow Definition Image - * @deprecated 5.0 not exposed in web-client web.xml - */ -public class WorkflowDefinitionImageServlet extends HttpServlet -{ - private static final long serialVersionUID = 1L; - - /* (non-Javadoc) - * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException - { - // retrieve workflow definition id - String uri = request.getRequestURI(); - uri = uri.substring(request.getContextPath().length()); - StringTokenizer t = new StringTokenizer(uri, "/"); - if (t.countTokens() != 2) - { - throw new WorkflowException("Workflow Definition Image servlet does not contain workflow definition id : " + uri); - } - t.nextToken(); // skip servlet name - String workflowDefinitionId = t.nextToken(); - - // retrieve workflow definition image - WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); - WorkflowService workflowService = (WorkflowService)wc.getBean(ServiceRegistry.WORKFLOW_SERVICE.getLocalName()); - byte[] definitionImage = workflowService.getDefinitionImage(workflowDefinitionId); - - // stream out through response - OutputStream out = response.getOutputStream(); - out.write(definitionImage); - out.flush(); - } - -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/ajax/AjaxCommand.java b/war/src/main/java/org/alfresco/web/app/servlet/ajax/AjaxCommand.java deleted file mode 100644 index 755ae4392f..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/ajax/AjaxCommand.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.ajax; - -import java.io.IOException; - -import javax.faces.context.FacesContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Interface for all Ajax commands executed by this servlet. - * - * The method is responsible for invoking the underlying managed bean - * and dealing with the response. - * - * @author gavinc - */ -public interface AjaxCommand -{ - /** - * Invokes the relevant method on the bean represented by the given - * expression. Parameters required to call the method can be retrieved - * from the request. - * - * Currently the content type of the response will always be text/xml, in the - * future sublcasses may provide a mechanism to allow the content type to be set - * dynamically. - * - * @param facesContext FacesContext - * @param expression The binding expression - * @param request The request - * @param response The response - */ - public abstract void execute(FacesContext facesContext, String expression, - HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException; -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/ajax/AjaxServlet.java b/war/src/main/java/org/alfresco/web/app/servlet/ajax/AjaxServlet.java deleted file mode 100644 index b44566e8a3..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/ajax/AjaxServlet.java +++ /dev/null @@ -1,222 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.ajax; - -import java.io.IOException; -import java.util.Enumeration; - -import javax.faces.context.FacesContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import net.sf.acegisecurity.context.ContextHolder; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.web.app.servlet.AuthenticationStatus; -import org.alfresco.web.app.servlet.BaseServlet; -import org.alfresco.web.app.servlet.FacesHelper; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Servlet responsible for processing AJAX requests. - * - * The URL to the servlet should be in the form: - *

/alfresco/ajax/command/Bean.binding.expression
- *

- * See http://wiki.alfresco.com/wiki/AJAX_Support for details. - *

- * Like most Alfresco servlets, the URL may be followed by a valid 'ticket' argument for authentication: - * ?ticket=1234567890 - * - * @author gavinc - * @deprecated 5.0 not exposed in web-client web.xml - */ -public class AjaxServlet extends BaseServlet -{ - public static final String AJAX_LOG_KEY = "alfresco.ajax"; - - protected enum Command { invoke, get, set}; - - private static final long serialVersionUID = -7654769105419391840L; - private static Log logger = LogFactory.getLog(AJAX_LOG_KEY); - private static Log headersLogger = LogFactory.getLog(AJAX_LOG_KEY + ".headers"); - private static Log perfLogger = LogFactory.getLog(AJAX_LOG_KEY + ".performance"); - - /** - * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - protected void service(final HttpServletRequest request, - final HttpServletResponse response) - throws ServletException, IOException - { - request.setCharacterEncoding("utf-8"); - // set default character encoding for the response - response.setCharacterEncoding("utf-8"); - response.setContentType("text/xml;charset=UTF-8"); - - long startTime = 0; - String uri = request.getRequestURI(); - if (logger.isDebugEnabled()) - { - final String queryString = request.getQueryString(); - logger.debug("Processing URL: " + uri + - ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : "")); - } - - // dump the request headers - if (headersLogger.isDebugEnabled()) - { - final Enumeration headers = request.getHeaderNames(); - while (headers.hasMoreElements()) - { - final String name = (String)headers.nextElement(); - headersLogger.debug(name + ": " + request.getHeader(name)); - } - } - - try - { - - // Make sure the user is authenticated, if not throw an error to return the - // 500 Internal Server Error code back to the client - AuthenticationStatus status = servletAuthenticate(request, response, false); - if (status == AuthenticationStatus.Failure) - { - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, - "Access Denied: User not authenticated"); - return; - } - - setNoCacheHeaders(response); - - uri = uri.substring(request.getContextPath().length() + "/".length()); - final String[] tokens = uri.split("/"); - if (tokens.length < 3) - { - throw new AlfrescoRuntimeException("Servlet URL did not contain all required args: " + uri); - } - - // retrieve the command from the URL - final String commandName = tokens[1]; - // retrieve the binding expression from the URL - final String expression = tokens[2]; - - // setup the faces context - final FacesContext facesContext = FacesHelper.getFacesContext(request, response, getServletContext()); - - // start a timer - if (perfLogger.isDebugEnabled()) - startTime = System.currentTimeMillis(); - - // instantiate the relevant command - AjaxCommand command = null; - if (Command.invoke.toString().equals(commandName)) - { - command = new InvokeCommand(); - } - else if (Command.get.toString().equals(commandName)) - { - command = new GetCommand(); - } - else - { - throw new AlfrescoRuntimeException("Unrecognised command received: " + commandName); - } - - // execute the command - command.execute(facesContext, expression, request, response); - } - catch (RuntimeException error) - { - handleError(response, error); - } - finally - { - // measure the time taken - if (perfLogger.isDebugEnabled()) - { - perfLogger.debug("Time to execute command: " + (System.currentTimeMillis() - startTime) + "ms"); - } - - ContextHolder.setContext(null); - } - } - - /** - * Handles any error that occurs during the execution of the servlet - * - * @param response The response - * @param cause The cause of the error - */ - protected void handleError(HttpServletResponse response, RuntimeException cause) - throws ServletException, IOException - { - // if we can send back the 500 error with the error from the top of the - // stack as the error status message. - - // NOTE: if we use the built in support for generating error pages for - // 500 errors we can tailor the output for AJAX calls so that the - // body of the response can be used to show the error details. - - if (!response.isCommitted()) - { - // dump the error if debugging is enabled - if (logger.isDebugEnabled()) - { - logger.error(cause); - Throwable theCause = cause.getCause(); - if (theCause != null) - { - logger.error("caused by: ", theCause); - } - } - - // extract a message from the exception - String msg = cause.getMessage(); - if (msg == null) - { - msg = cause.toString(); - } - // ALF-9036. We need to trap incomplete sessions - if (cause instanceof IllegalStateException) - { - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, cause.getMessage()); - } - else - { - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); - } - } - else - { - // the response has already been comitted, not much we can do but - // let the error through and let the container deal with it - throw cause; - } - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/ajax/BaseAjaxCommand.java b/war/src/main/java/org/alfresco/web/app/servlet/ajax/BaseAjaxCommand.java deleted file mode 100644 index 33ca134312..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/ajax/BaseAjaxCommand.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.ajax; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Base class for all Ajax based commands - * - * @author gavinc - */ -public abstract class BaseAjaxCommand implements AjaxCommand -{ - protected static Log logger = LogFactory.getLog(AjaxServlet.AJAX_LOG_KEY); - - public String makeBindingExpression(String expression) - { - return "#{" + expression + "}"; - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/ajax/GetCommand.java b/war/src/main/java/org/alfresco/web/app/servlet/ajax/GetCommand.java deleted file mode 100644 index 54d2bb46b2..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/ajax/GetCommand.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.ajax; - -import java.io.IOException; - -import javax.faces.context.FacesContext; -import javax.faces.el.ValueBinding; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.transaction.UserTransaction; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.web.bean.repository.Repository; - -/** - * Command that executes the given value binding expression. - *

- * This command is intended to be used for calling existing managed - * bean methods. The result of the value binding is added to - * the response as is i.e. by calling toString(). - * The content type of the response is always text/html. - * - * @author gavinc - */ -public class GetCommand extends BaseAjaxCommand -{ - public void execute(FacesContext facesContext, String expression, - HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException - { - // create the JSF binding expression - String bindingExpr = makeBindingExpression(expression); - - if (logger.isDebugEnabled()) - logger.debug("Retrieving value from value binding: " + bindingExpr); - - UserTransaction tx = null; - try - { - // create the value binding - ValueBinding binding = facesContext.getApplication(). - createValueBinding(bindingExpr); - - if (binding != null) - { - // setup the transaction - tx = Repository.getUserTransaction(facesContext, true); - tx.begin(); - - // get the value from the value binding - Object value = binding.getValue(facesContext); - if (value != null) - { - response.getWriter().write(value.toString()); - } - - // commit - tx.commit(); - } - } - catch (Throwable err) - { - // rollback the transaction - try { if (tx != null) {tx.rollback();} } catch (Exception ex) {} - - throw new AlfrescoRuntimeException("Failed to retrieve value: " + err.getMessage(), err); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/ajax/InvokeCommand.java b/war/src/main/java/org/alfresco/web/app/servlet/ajax/InvokeCommand.java deleted file mode 100644 index fb34de6951..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/ajax/InvokeCommand.java +++ /dev/null @@ -1,243 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.ajax; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Enumeration; - -import javax.faces.FactoryFinder; -import javax.faces.component.UIViewRoot; -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; -import javax.faces.el.EvaluationException; -import javax.faces.el.VariableResolver; -import javax.faces.render.RenderKit; -import javax.faces.render.RenderKitFactory; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.repo.transaction.RetryingTransactionHelper; -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Repository; - -/** - * Command that invokes the method represented by the expression. - *

- * The managed bean method called is responsible for writing the response - * by getting hold of the JSF ResponseWriter. Parameters can also be - * retrieved via the JSF ExternalContext object. - *

- * In a future release (if required) annotations may be used to state - * what content type to use for the response. - * - * @author gavinc - */ -public class InvokeCommand extends BaseAjaxCommand -{ - - ///////////////////////////////////////////////////////////////////////////// - - /** - * Annotation for a bean method that handles an ajax request. - */ - @Retention(RetentionPolicy.RUNTIME) - @Target(ElementType.METHOD) - public @interface ResponseMimetype - { - // NOTE: replaced Mimetype.MIMETYPE_XML with string literal due to bug - // http://bugs.sun.com/view_bug.do?bug_id=6512707 - causing build to fail - public String value() default "text/xml"; - } - - ///////////////////////////////////////////////////////////////////////////// - - public void execute(final FacesContext facesContext, - final String expression, - final HttpServletRequest request, - final HttpServletResponse response) - throws ServletException, IOException - { - ResponseWriter writer = null; - try - { - final int indexOfDot = expression.indexOf('.'); - final String variableName = expression.substring(0, indexOfDot); - final String methodName = expression.substring(indexOfDot + 1); - - if (logger.isDebugEnabled()) - logger.debug("Invoking method represented by " + expression + - " on variable " + variableName + - " with method " + methodName); - - Object bean = null; - if (Application.inPortalServer()) - { - // retrieve the managed bean, this is really weak but if the - // request comes from a portal server the bean we need to get - // is in the session with a prefix chosen by the portal vendor, - // to cover this scenario we have to go through the names of - // all the objects in the session to find the bean we want. - - String beanNameSuffix = "?" + variableName; - Enumeration enumNames = request.getSession().getAttributeNames(); - while (enumNames.hasMoreElements()) - { - String name = (String)enumNames.nextElement(); - if (name.endsWith(beanNameSuffix)) - { - bean = request.getSession().getAttribute(name); - - if (logger.isDebugEnabled()) - logger.debug("Found bean " + bean + " in the session"); - - break; - } - } - } - - // if we don't have the bean yet try and get it via the variable resolver - if (bean == null) - { - VariableResolver vr = facesContext.getApplication().getVariableResolver(); - bean = vr.resolveVariable(facesContext, variableName); - - if (logger.isDebugEnabled()) - logger.debug("Created bean " + bean + " via the variable resolver"); - } - - final Method method = bean.getClass().getMethod(methodName); - - final String responseMimetype = - (method.isAnnotationPresent(ResponseMimetype.class) - ? method.getAnnotation(ResponseMimetype.class).value() - : MimetypeMap.MIMETYPE_XML); - - if (logger.isDebugEnabled()) - logger.debug("invoking method " + method + - " with repsonse mimetype " + responseMimetype); - - writer = this.setupResponseWriter(responseMimetype, - response, - facesContext); - - // setup the transaction - RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(FacesContext.getCurrentInstance()); - final Object beanFinal = bean; - RetryingTransactionCallback callback = new RetryingTransactionCallback() - { - public Object execute() throws Throwable - { - // invoke the method - try - { - method.invoke(beanFinal); - return null; - } - // Let's prevent RuntimeExceptions being wrapped twice by unwrapping InvocationTargetExceptions - catch (InvocationTargetException e) - { - if (e.getCause() != null) - { - throw e.getCause(); - } - throw e; - } - } - }; - txnHelper.doInTransaction(callback); - } - catch (EvaluationException e) - { - Throwable err = e.getCause(); - if (err == null) - { - logger.error("Failed to execute method " + expression + ": " + e.getMessage(), e); - throw e; - } - else - { - logger.error("Failed to execute method " + expression + ": " + err.getMessage(), err); - if (err instanceof RuntimeException) - { - throw (RuntimeException)err; - } - else - { - throw new AlfrescoRuntimeException("Failed to execute method " + expression + ": " + err.getMessage(), err); - } - } - } - catch (RuntimeException err) - { - - logger.error("Failed to execute method " + expression + ": " + err.getMessage(), err); - throw err; - } - catch (Exception err) - { - - logger.error("Failed to execute method " + expression + ": " + err.getMessage(), err); - throw new AlfrescoRuntimeException("Failed to execute method " + expression + ": " + err.getMessage(), err); - } - - // force the output back to the client - writer.close(); - } - - /** setup the JSF response writer. */ - private ResponseWriter setupResponseWriter(final String mimetype, - final HttpServletResponse response, - final FacesContext facesContext) - throws IOException - { - final OutputStream os = response.getOutputStream(); - final UIViewRoot viewRoot = facesContext.getViewRoot(); - final RenderKitFactory renderFactory = (RenderKitFactory) - FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); - final RenderKit renderKit = - renderFactory.getRenderKit(facesContext, viewRoot.getRenderKitId()); - final ResponseWriter writer = - renderKit.createResponseWriter(new OutputStreamWriter(os, "UTF-8"), - mimetype, - "UTF-8"); - facesContext.setResponseWriter(writer); - // must be text/xml otherwise IE doesn't parse the response properly into responseXML - response.setContentType(mimetype); - return writer; - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/command/ApproveWorkflowCommand.java b/war/src/main/java/org/alfresco/web/app/servlet/command/ApproveWorkflowCommand.java deleted file mode 100644 index 06a0a1baa3..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/command/ApproveWorkflowCommand.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.command; - -import java.util.Map; - -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.bean.workflow.WorkflowUtil; - -/** - * Approve Workflow command implementation - * - * @author Kevin Roast - */ -public final class ApproveWorkflowCommand implements Command -{ - public static final String PROP_TARGET = "target"; - - private static final String[] PROPERTIES = new String[] {PROP_TARGET}; - - /** - * @see org.alfresco.web.app.servlet.command.Command#getPropertyNames() - */ - public String[] getPropertyNames() - { - return PROPERTIES; - } - - /** - * @see org.alfresco.web.app.servlet.command.Command#execute(org.alfresco.service.ServiceRegistry, java.util.Map) - */ - public Object execute(ServiceRegistry serviceRegistry, Map properties) - { - // get the target Node for the command - NodeRef nodeRef = (NodeRef)properties.get(PROP_TARGET); - if (nodeRef == null) - { - throw new IllegalArgumentException( - "Unable to execute ApproveCommand - mandatory parameter not supplied: " + PROP_TARGET); - } - - WorkflowUtil.approve(nodeRef, serviceRegistry.getNodeService(), serviceRegistry.getCopyService()); - - return true; - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/command/BaseNodeCommandProcessor.java b/war/src/main/java/org/alfresco/web/app/servlet/command/BaseNodeCommandProcessor.java deleted file mode 100644 index b22cdd3b98..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/command/BaseNodeCommandProcessor.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.command; - -import java.util.Map; - -import javax.servlet.ServletContext; - -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.StoreRef; -import org.alfresco.service.cmr.security.AccessStatus; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.web.bean.repository.Repository; - -/** - * Initial implementation of a Command Processor that is always passed enough URL elements - * to construct a single NodeRef argument. The NodeRef is checked against READ permissions - * for the current user during the validateArguments() call. - *

- * This class should be enough to form the base of Command Processor objects that only require - * a single NodeRef passed on the URL. - * - * @author Kevin Roast - */ -public abstract class BaseNodeCommandProcessor implements CommandProcessor -{ - protected NodeRef targetRef; - - /** - * @see org.alfresco.web.app.servlet.command.CommandProcessor#validateArguments(javax.servlet.ServletContext, java.lang.String, java.util.Map, java.lang.String[]) - */ - public boolean validateArguments(ServletContext sc, String command, Map args, String[] urlElements) - { - if (urlElements.length < 3) - { - throw new IllegalArgumentException("Not enough URL arguments passed to command servlet."); - } - - // get NodeRef to the node with the workflow attached to it - StoreRef storeRef = new StoreRef(urlElements[0], urlElements[1]); - this.targetRef = new NodeRef(storeRef, urlElements[2]); - - // get the services we need to execute the workflow command - PermissionService permissionService = Repository.getServiceRegistry(sc).getPermissionService(); - - // check that the user has at least READ access on the node - else redirect to the login page - return (permissionService.hasPermission(this.targetRef, PermissionService.READ) == AccessStatus.ALLOWED); - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/command/BaseUIActionCommand.java b/war/src/main/java/org/alfresco/web/app/servlet/command/BaseUIActionCommand.java deleted file mode 100644 index ba9606a3ab..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/command/BaseUIActionCommand.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.command; - -import java.util.Map; - -import org.alfresco.service.ServiceRegistry; - -/** - * @author Kevin Roast - */ -public abstract class BaseUIActionCommand implements Command -{ - public static final String PROP_SERVLETCONTEXT = "ServletContext"; - public static final String PROP_REQUEST = "Request"; - public static final String PROP_RESPONSE = "Response"; -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/command/Command.java b/war/src/main/java/org/alfresco/web/app/servlet/command/Command.java deleted file mode 100644 index cbbd6b8d39..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/command/Command.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.command; - -import java.util.Map; - -import org.alfresco.service.ServiceRegistry; - -/** - * Simple servlet command pattern interface. - * - * @author Kevin Roast - */ -public interface Command -{ - /** - * Execute the command - * - * @param serviceRegistry The ServiceRegistry instance - * @param properties Bag of named properties for the command - * - * @return return value from the command if any - */ - public Object execute(ServiceRegistry serviceRegistry, Map properties); - - /** - * @return the names of the properties required for this command - */ - public String[] getPropertyNames(); -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/command/CommandFactory.java b/war/src/main/java/org/alfresco/web/app/servlet/command/CommandFactory.java deleted file mode 100644 index 6a8da371cb..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/command/CommandFactory.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.command; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Command Factory helper - * - * @author Kevin Roast - */ -public final class CommandFactory -{ - private static Log logger = LogFactory.getLog(CommandFactory.class); - - private static CommandFactory instance = new CommandFactory(); - - private static Map registry = new HashMap(16, 1.0f); - - /** - * Private constructor - protect the singleton instance - */ - private CommandFactory() - { - } - - /** - * @return the singleton CommandFactory instance - */ - public static CommandFactory getInstance() - { - return instance; - } - - /** - * Register a command name against an implementation - * - * @param name Unique name of the command - * @param clazz Class implementation of the command - */ - public void registerCommand(String name, Class clazz) - { - registry.put(name, clazz); - } - - /** - * Create a command instance of the specified command name - * - * @param name Name of the command to create (must be registered) - * - * @return the Command instance or null if not found - */ - public Command createCommand(String name) - { - Command result = null; - - // lookup command by name in the registry - Class clazz = registry.get(name); - if (clazz != null) - { - try - { - Object obj = clazz.newInstance(); - if (obj instanceof Command) - { - result = (Command)obj; - } - } - catch (Throwable err) - { - // return default if this occurs - logger.warn("Unable to create workflow command instance '" + name + - "' with classname '" + clazz.getName() + "' due to error: " + err.getMessage()); - } - } - - return result; - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/command/CommandProcessor.java b/war/src/main/java/org/alfresco/web/app/servlet/command/CommandProcessor.java deleted file mode 100644 index 129d4fb892..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/command/CommandProcessor.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.command; - -import java.io.PrintWriter; -import java.util.Map; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; - -import org.alfresco.service.ServiceRegistry; - -/** - * This interfaces defines the contract and lifecycle of a Servlet Command Processor. - *

- * A command processor is defined as a class capable of executing a set of related Command - * objects. It performs the bulk of the work for the command servlet. The processor impl - * is responsible for validating that the command can be processed (given the supplied remaining - * URL arguments from the servlet) and processing the command. It is also responsible for - * supply an output status page on successfuly execution of the command. - *

- * The arguments passed to a Command Processor are the remaining URL elements from the command - * servlet URL after removing the web-app name, servlet name and command processor name. - * - * @author Kevin Roast - */ -public interface CommandProcessor -{ - /** - * Pass and validate URL arguments for the command processor. Validate if the command can be - * executed given the arguments supplied. Generally at this post a Command Processor will - * convert the supplied arguments to the objects it expects, and also check any permissions - * that are required by the current user to execute the command. - * - * @param sc ServletContext, can be used to retrieve ServiceRegistry instance - * from the Repository bean. - * @param command Name of the command the arguments are for - * @param args Map of URL args passed to the command servlet - * @param urlElements String[] of the remaining URL arguments to the command servlet - * - * @return true if the command can be executed by the current user given the supplied args. - */ - public boolean validateArguments(ServletContext sc, String command, Map args, String[] urlElements); - - /** - * Process the supplied command name. It is the responsibility of the Command Processor - * to lookup the specified command name using the CommandFactory registry. For that reason - * it also has the responsiblity to initially register commands it is responsible for so - * they can be constructed later. If the supplied command is unknown to it then an - * exception should be thrown to indicate this. - * - * @param serviceRegistry ServiceRegistry - * @param request HttpServletRequest - * @param command Name of the command to construct and execute - */ - public void process(ServiceRegistry serviceRegistry, HttpServletRequest request, String command); - - /** - * Output a simple status message to the supplied PrintWriter. - * It can be assumed that the process() method was successful if this method is called. - * - * @param out PrintWriter - */ - public void outputStatus(PrintWriter out); -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/command/EditContentPropertiesCommand.java b/war/src/main/java/org/alfresco/web/app/servlet/command/EditContentPropertiesCommand.java deleted file mode 100644 index 8d0a7f26de..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/command/EditContentPropertiesCommand.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.command; - -import java.util.Map; - -import javax.faces.application.NavigationHandler; -import javax.faces.context.FacesContext; -import javax.servlet.ServletContext; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.NodeRef; -import org.springframework.extensions.surf.util.ParameterCheck; -import org.alfresco.web.app.servlet.BaseServlet; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.BrowseBean; -import org.alfresco.web.bean.repository.Node; - -/** - * Command to execute the Edit Content Properties dialog via url. - *

- * Arguments: noderef - of the document to show the edit props dialog for - * - * @author Kevin Roast - */ -public class EditContentPropertiesCommand extends BaseUIActionCommand -{ - public static final String PROP_NODEREF = "noderef"; - - private static final String[] PROPERTIES = new String[] { - PROP_SERVLETCONTEXT, PROP_REQUEST, PROP_RESPONSE, PROP_NODEREF}; - - /** - * @see org.alfresco.web.app.servlet.command.Command#execute(org.alfresco.service.ServiceRegistry, java.util.Map) - */ - public Object execute(ServiceRegistry serviceRegistry, Map properties) - { - ServletContext sc = (ServletContext)properties.get(PROP_SERVLETCONTEXT); - ServletRequest req = (ServletRequest)properties.get(PROP_REQUEST); - ServletResponse res = (ServletResponse)properties.get(PROP_RESPONSE); - FacesContext fc = FacesHelper.getFacesContext(req, res, sc, "/jsp/close.jsp"); - BrowseBean browseBean = (BrowseBean)FacesHelper.getManagedBean(fc, BrowseBean.BEAN_NAME); - - // setup context from url args in properties map - String strNodeRef = (String)properties.get(PROP_NODEREF); - ParameterCheck.mandatoryString(PROP_NODEREF, strNodeRef); - browseBean.setDocument(new Node(new NodeRef(strNodeRef))); - - NavigationHandler navigationHandler = fc.getApplication().getNavigationHandler(); - navigationHandler.handleNavigation(fc, null, "dialog:editContentProperties"); - String viewId = fc.getViewRoot().getViewId(); - try - { - sc.getRequestDispatcher(BaseServlet.FACES_SERVLET + viewId).forward(req, res); - } - catch (Exception e) - { - throw new AlfrescoRuntimeException("Unable to forward to viewId: " + viewId, e); - } - - return null; - } - - /** - * @see org.alfresco.web.app.servlet.command.Command#getPropertyNames() - */ - public String[] getPropertyNames() - { - return PROPERTIES; - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/command/EditSpaceCommand.java b/war/src/main/java/org/alfresco/web/app/servlet/command/EditSpaceCommand.java deleted file mode 100755 index 0ea94b9cc2..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/command/EditSpaceCommand.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.command; - -import java.util.Map; - -import javax.faces.application.NavigationHandler; -import javax.faces.context.FacesContext; -import javax.servlet.ServletContext; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.NodeRef; -import org.springframework.extensions.surf.util.ParameterCheck; -import org.alfresco.web.app.servlet.BaseServlet; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.BrowseBean; -import org.alfresco.web.bean.repository.Node; - -/** - * Command to execute the Edit Space dialog via url. - *

- * Arguments: noderef - of the space to show the edit props dialog for - * - * @author Pavel Yurkevich - */ -public class EditSpaceCommand extends BaseUIActionCommand -{ - public static final String PROP_NODEREF = "noderef"; - - private static final String[] PROPERTIES = new String[] { - PROP_SERVLETCONTEXT, PROP_REQUEST, PROP_RESPONSE, PROP_NODEREF}; - - /** - * @see org.alfresco.web.app.servlet.command.Command#execute(org.alfresco.service.ServiceRegistry, java.util.Map) - */ - public Object execute(ServiceRegistry serviceRegistry, Map properties) - { - ServletContext sc = (ServletContext)properties.get(PROP_SERVLETCONTEXT); - ServletRequest req = (ServletRequest)properties.get(PROP_REQUEST); - ServletResponse res = (ServletResponse)properties.get(PROP_RESPONSE); - FacesContext fc = FacesHelper.getFacesContext(req, res, sc, "/jsp/close.jsp"); - BrowseBean browseBean = (BrowseBean)FacesHelper.getManagedBean(fc, BrowseBean.BEAN_NAME); - - // setup context from url args in properties map - String strNodeRef = (String)properties.get(PROP_NODEREF); - ParameterCheck.mandatoryString(PROP_NODEREF, strNodeRef); - browseBean.setActionSpace(new Node(new NodeRef(strNodeRef))); - - NavigationHandler navigationHandler = fc.getApplication().getNavigationHandler(); - navigationHandler.handleNavigation(fc, null, "dialog:editSpace"); - String viewId = fc.getViewRoot().getViewId(); - try - { - sc.getRequestDispatcher(BaseServlet.FACES_SERVLET + viewId).forward(req, res); - } - catch (Exception e) - { - throw new AlfrescoRuntimeException("Unable to forward to viewId: " + viewId, e); - } - - return null; - } - - /** - * @see org.alfresco.web.app.servlet.command.Command#getPropertyNames() - */ - public String[] getPropertyNames() - { - return PROPERTIES; - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/command/EndTaskCommand.java b/war/src/main/java/org/alfresco/web/app/servlet/command/EndTaskCommand.java deleted file mode 100644 index 8762c86203..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/command/EndTaskCommand.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.command; - -import java.util.Map; - -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.workflow.WorkflowService; - -/** - * End Task command implementation - * - * @author David Caruana - */ -public final class EndTaskCommand implements Command -{ - public static final String PROP_TASK_ID = "taskId"; - public static final String PROP_TRANSITION = "transition"; - - private static final String[] PROPERTIES = new String[] {PROP_TASK_ID, PROP_TRANSITION}; - - /** - * @see org.alfresco.web.app.servlet.command.Command#getPropertyNames() - */ - public String[] getPropertyNames() - { - return PROPERTIES; - } - - /** - * @see org.alfresco.web.app.servlet.command.Command#execute(org.alfresco.service.ServiceRegistry, java.util.Map) - */ - public Object execute(ServiceRegistry serviceRegistry, Map properties) - { - String taskId = (String)properties.get(PROP_TASK_ID); - if (taskId == null) - { - throw new IllegalArgumentException("Unable to execute EndTaskCommand - mandatory parameter not supplied: " + PROP_TASK_ID); - } - String transition = (String)properties.get(PROP_TRANSITION); - - // end task - WorkflowService workflowService = serviceRegistry.getWorkflowService(); - return workflowService.endTask(taskId, transition); - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/command/ExecuteScriptCommand.java b/war/src/main/java/org/alfresco/web/app/servlet/command/ExecuteScriptCommand.java deleted file mode 100644 index 055834ce46..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/command/ExecuteScriptCommand.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.command; - -import java.util.Map; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Repository; - -/** - * Execute Script command implementation. - *

- * Executes the supplied script against the default data-model. - * - * @author Kevin Roast - */ -public final class ExecuteScriptCommand implements Command -{ - public static final String PROP_SCRIPT = "script"; - public static final String PROP_DOCUMENT = "document"; - public static final String PROP_USERPERSON = "person"; - public static final String PROP_ARGS = "args"; - - private static final String[] PROPERTIES = new String[] {PROP_SCRIPT, PROP_DOCUMENT, PROP_USERPERSON, PROP_ARGS}; - - - /** - * @see org.alfresco.web.app.servlet.command.Command#getPropertyNames() - */ - public String[] getPropertyNames() - { - return PROPERTIES; - } - - /** - * @see org.alfresco.web.app.servlet.command.Command#execute(org.alfresco.service.ServiceRegistry, java.util.Map) - */ - public Object execute(ServiceRegistry serviceRegistry, Map properties) - { - // get the target Script node for the command - NodeRef scriptRef = (NodeRef)properties.get(PROP_SCRIPT); - if (scriptRef == null) - { - throw new IllegalArgumentException( - "Unable to execute ExecuteScriptCommand - mandatory parameter not supplied: " + PROP_SCRIPT); - } - - NodeRef personRef = (NodeRef)properties.get(PROP_USERPERSON); - if (personRef == null) - { - throw new IllegalArgumentException( - "Unable to execute ExecuteScriptCommand - mandatory parameter not supplied: " + PROP_USERPERSON); - } - - // get the optional document and space context ref - NodeService nodeService = serviceRegistry.getNodeService(); - NodeRef docRef = (NodeRef)properties.get(PROP_DOCUMENT); - NodeRef spaceRef = null; - if (docRef != null) - { - spaceRef = nodeService.getPrimaryParent(docRef).getParentRef(); - } - - // build the model needed to execute the script - Map model = serviceRegistry.getScriptService().buildDefaultModel( - personRef, - new NodeRef(Repository.getStoreRef(), Application.getCompanyRootId()), - (NodeRef)nodeService.getProperty(personRef, ContentModel.PROP_HOMEFOLDER), - scriptRef, - docRef, - spaceRef); - - // add the url arguments map - model.put("args", properties.get(PROP_ARGS)); - - // execute the script and return the result - return serviceRegistry.getScriptService().executeScript(scriptRef, null, model); - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/command/ExtCommandProcessor.java b/war/src/main/java/org/alfresco/web/app/servlet/command/ExtCommandProcessor.java deleted file mode 100644 index 14df52d6f5..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/command/ExtCommandProcessor.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.command; - -import java.io.PrintWriter; -import java.util.Map; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.service.ServiceRegistry; - -/** - * This interfaces defines the contract and lifecycle of a Servlet Command Processor. - *

- * The ExtCommandProcessor adds an overloaded process() method to allow the - * HttpServletResponse to be passed. - * - * @author Kevin Roast - */ -public interface ExtCommandProcessor extends CommandProcessor -{ - /** - * Process the supplied command name. It is the responsibility of the Command Processor - * to lookup the specified command name using the CommandFactory registry. For that reason - * it also has the responsiblity to initially register commands it is responsible for so - * they can be constructed later. If the supplied command is unknown to it then an - * exception should be thrown to indicate this. - * - * @param serviceRegistry ServiceRegistry - * @param request HttpServletRequest - * @param response HttpServletResponse - * @param command Name of the command to construct and execute - */ - public void process(ServiceRegistry serviceRegistry, HttpServletRequest request, HttpServletResponse response, String command); -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/command/ManageTaskDialogCommand.java b/war/src/main/java/org/alfresco/web/app/servlet/command/ManageTaskDialogCommand.java deleted file mode 100644 index 1f6373b3c7..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/command/ManageTaskDialogCommand.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.command; - -import java.util.Map; - -import javax.faces.application.NavigationHandler; -import javax.faces.context.FacesContext; -import javax.servlet.ServletContext; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.web.app.servlet.BaseServlet; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.workflow.WorkflowBean; -import org.springframework.extensions.surf.util.ParameterCheck; - -/** - * Command to execute the Manage Task dialog via url. - *

- * Arguments: id = the id of the task - * type = the qname type of the task - * - * @author Kevin Roast - */ -public class ManageTaskDialogCommand extends BaseUIActionCommand -{ - public static final String PROP_TASKID = "id"; - public static final String PROP_TASKTYPE = "type"; - - private static final String[] PROPERTIES = new String[] { - PROP_SERVLETCONTEXT, PROP_REQUEST, PROP_RESPONSE, PROP_TASKID, PROP_TASKTYPE}; - - /** - * @see org.alfresco.web.app.servlet.command.Command#execute(org.alfresco.service.ServiceRegistry, java.util.Map) - */ - public Object execute(ServiceRegistry serviceRegistry, Map properties) - { - ServletContext sc = (ServletContext)properties.get(PROP_SERVLETCONTEXT); - ServletRequest req = (ServletRequest)properties.get(PROP_REQUEST); - ServletResponse res = (ServletResponse)properties.get(PROP_RESPONSE); - FacesContext fc = FacesHelper.getFacesContext(req, res, sc, "/jsp/close.jsp"); - WorkflowBean wfBean = (WorkflowBean)FacesHelper.getManagedBean(fc, WorkflowBean.BEAN_NAME); - - // setup dialog context from url args in properties map - String taskId = (String)properties.get(PROP_TASKID); - ParameterCheck.mandatoryString(PROP_TASKID, taskId); - String taskType = (String)properties.get(PROP_TASKTYPE); - ParameterCheck.mandatoryString(PROP_TASKTYPE, taskType); - - wfBean.setupTaskDialog(taskId, taskType); - - NavigationHandler navigationHandler = fc.getApplication().getNavigationHandler(); - navigationHandler.handleNavigation(fc, null, "dialog:manageTask"); - String viewId = fc.getViewRoot().getViewId(); - try - { - sc.getRequestDispatcher(BaseServlet.FACES_SERVLET + viewId).forward(req, res); - } - catch (Exception e) - { - throw new AlfrescoRuntimeException("Unable to forward to viewId: " + viewId, e); - } - - return null; - } - - /** - * @see org.alfresco.web.app.servlet.command.Command#getPropertyNames() - */ - public String[] getPropertyNames() - { - return PROPERTIES; - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/command/RejectWorkflowCommand.java b/war/src/main/java/org/alfresco/web/app/servlet/command/RejectWorkflowCommand.java deleted file mode 100644 index 61d0b487a9..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/command/RejectWorkflowCommand.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.command; - -import java.util.Map; - -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.bean.workflow.WorkflowUtil; - -/** - * Reject Workflow command implementation - * - * @author Kevin Roast - */ -public final class RejectWorkflowCommand implements Command -{ - public static final String PROP_TARGET = "target"; - - private static final String[] PROPERTIES = new String[] {PROP_TARGET}; - - /** - * @see org.alfresco.web.app.servlet.command.Command#getPropertyNames() - */ - public String[] getPropertyNames() - { - return PROPERTIES; - } - - /** - * @see org.alfresco.web.app.servlet.command.Command#execute(org.alfresco.service.ServiceRegistry, java.util.Map) - */ - public Object execute(ServiceRegistry serviceRegistry, Map properties) - { - // get the target Node for the command - NodeRef nodeRef = (NodeRef)properties.get(PROP_TARGET); - if (nodeRef == null) - { - throw new IllegalArgumentException( - "Unable to execute RejectCommand - mandatory parameter not supplied: " + PROP_TARGET); - } - - WorkflowUtil.reject(nodeRef, serviceRegistry.getNodeService(), serviceRegistry.getCopyService()); - - return true; - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/command/ScriptCommandProcessor.java b/war/src/main/java/org/alfresco/web/app/servlet/command/ScriptCommandProcessor.java deleted file mode 100644 index 5c530eeae4..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/command/ScriptCommandProcessor.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.command; - -import java.io.PrintWriter; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.repo.jscript.ScriptableHashMap; -import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.StoreRef; -import org.alfresco.service.cmr.security.AccessStatus; -import org.alfresco.service.cmr.security.AuthorityService; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.servlet.BaseServlet; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.repository.User; -import org.alfresco.web.config.ClientConfigElement; -import org.springframework.extensions.config.ConfigService; - -/** - * Script command processor implementation. - *

- * Responsible for executing 'execute' script commands on a Node. - * - * @author Kevin Roast - */ -public final class ScriptCommandProcessor implements CommandProcessor -{ - private static final String ARG_SCRIPT_PATH = "scriptPath"; - private static final String ARG_CONTEXT_PATH = "contextPath"; - - private NodeRef scriptRef; - private NodeRef docRef; - private Object result; - - static - { - // add our commands to the command registry - CommandFactory.getInstance().registerCommand("execute", ExecuteScriptCommand.class); - } - - - /** - * @see org.alfresco.web.app.servlet.command.CommandProcessor#validateArguments(javax.servlet.ServletContext, java.lang.String, java.util.Map, java.lang.String[]) - */ - public boolean validateArguments(ServletContext sc, String command, Map args, String[] urlElements) - { - boolean allowed = false; - String scriptPath = args.get(ARG_SCRIPT_PATH); - if (scriptPath != null) - { - // resolve path to a node - this.scriptRef = BaseServlet.resolveNamePath(sc, scriptPath).NodeRef; - - // same for the document context path if specified - String docPath = args.get(ARG_CONTEXT_PATH); - if (docPath != null) - { - this.docRef = BaseServlet.resolveNamePath(sc, docPath).NodeRef; - } - } - else - { - if (urlElements.length < 3) - { - throw new IllegalArgumentException("Not enough URL arguments passed to command servlet."); - } - - // get NodeRef to the node script to execute - StoreRef storeRef = new StoreRef(urlElements[0], urlElements[1]); - this.scriptRef = new NodeRef(storeRef, urlElements[2]); - - if (urlElements.length >= 6) - { - storeRef = new StoreRef(urlElements[3], urlElements[4]); - this.docRef = new NodeRef(storeRef, urlElements[5]); - } - } - - // check we can READ access the nodes specified - PermissionService ps = Repository.getServiceRegistry(sc).getPermissionService(); - allowed = (ps.hasPermission(this.scriptRef, PermissionService.READ) == AccessStatus.ALLOWED); - if (this.docRef != null) - { - allowed &= (ps.hasPermission(this.docRef, PermissionService.READ) == AccessStatus.ALLOWED); - } - - // check to see if user is allowed to execute arbituary javascript - // by default only an admin authority can perform this action - ConfigService configService = Application.getConfigService(sc); - ClientConfigElement configElement = (ClientConfigElement)configService.getGlobalConfig().getConfigElement("client"); - boolean allowScriptExecute = configElement.getAllowUserScriptExecute(); - AuthorityService authService = Repository.getServiceRegistry(sc).getAuthorityService(); - allowed &= (allowScriptExecute || authService.isAdminAuthority(AuthenticationUtil.getFullyAuthenticatedUser())); - - return allowed; - } - - /** - * @see org.alfresco.web.app.servlet.command.CommandProcessor#process(org.alfresco.service.ServiceRegistry, javax.servlet.http.HttpServletRequest, java.lang.String) - */ - public void process(ServiceRegistry serviceRegistry, HttpServletRequest request, String command) - { - Map properties = new HashMap(4, 1.0f); - - properties.put(ExecuteScriptCommand.PROP_SCRIPT, this.scriptRef); - properties.put(ExecuteScriptCommand.PROP_DOCUMENT, this.docRef); - User user = Application.getCurrentUser(request.getSession()); - properties.put(ExecuteScriptCommand.PROP_USERPERSON, user.getPerson()); - - // add URL arguments as a special Scriptable Map property called 'args' - Map args = new ScriptableHashMap(); - Enumeration names = request.getParameterNames(); - while (names.hasMoreElements()) - { - String name = (String)names.nextElement(); - args.put(name, request.getParameter(name)); - } - properties.put(ExecuteScriptCommand.PROP_ARGS, args); - - Command cmd = CommandFactory.getInstance().createCommand(command); - if (cmd == null) - { - throw new AlfrescoRuntimeException("Unregistered script command specified: " + command); - } - this.result = cmd.execute(serviceRegistry, properties); - } - - /** - * @see org.alfresco.web.app.servlet.command.CommandProcessor#outputStatus(java.io.PrintWriter) - */ - public void outputStatus(PrintWriter out) - { - out.write(this.result != null ? this.result.toString() : "Successfully executed script."); - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/command/TaskCommandProcessor.java b/war/src/main/java/org/alfresco/web/app/servlet/command/TaskCommandProcessor.java deleted file mode 100644 index 32891797f5..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/command/TaskCommandProcessor.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.command; - -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.web.bean.workflow.WorkflowUtil; -import org.alfresco.web.ui.common.Utils; - -/** - * Task specific command processor implementation. - *

- * Responsible for executing workflow task operations. - * - * @author David Caruana - */ -public final class TaskCommandProcessor implements CommandProcessor -{ - private String taskId; - private String transition = null; - private String command; - - static - { - // add our commands to the command registry - CommandFactory.getInstance().registerCommand("end", EndTaskCommand.class); - } - - - /* (non-Javadoc) - * @see org.alfresco.web.app.servlet.command.CommandProcessor#validateArguments(javax.servlet.ServletContext, java.lang.String, java.util.Map, java.lang.String[]) - */ - public boolean validateArguments(ServletContext sc, String cmd, Map args, String[] urlElements) - { - if (urlElements.length == 0) - { - throw new IllegalArgumentException("Not enough URL arguments passed to command servlet."); - } - taskId = urlElements[0]; - if (urlElements.length == 2) - { - transition = urlElements[1]; - } - return WorkflowUtil.isTaskEditable(taskId, sc); - } - - /** - * @see org.alfresco.web.app.servlet.command.CommandProcessor#process(org.alfresco.service.ServiceRegistry, javax.servlet.http.HttpServletRequest, java.lang.String) - */ - public void process(ServiceRegistry serviceRegistry, HttpServletRequest request, String commandName) - { - Map properties = new HashMap(1, 1.0f); - // all workflow commands use a "target" Node property as an argument - properties.put(EndTaskCommand.PROP_TASK_ID, taskId); - if (transition != null) - { - properties.put(EndTaskCommand.PROP_TRANSITION, transition); - } - Command cmd = CommandFactory.getInstance().createCommand(commandName); - if (cmd == null) - { - throw new AlfrescoRuntimeException("Unregistered workflow command specified: " + commandName); - } - cmd.execute(serviceRegistry, properties); - this.command = commandName; - } - - /** - * @see org.alfresco.web.app.servlet.command.CommandProcessor#outputStatus(java.io.PrintWriter) - */ - public void outputStatus(PrintWriter out) - { - out.print("Task command: '"); - out.print(Utils.encode(command)); - out.print("' executed against task: "); - out.println(Utils.encode(taskId)); - } - -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/command/UIActionCommandProcessor.java b/war/src/main/java/org/alfresco/web/app/servlet/command/UIActionCommandProcessor.java deleted file mode 100644 index 918d1c29a1..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/command/UIActionCommandProcessor.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.command; - -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.bean.workflow.WorkflowUtil; -import org.alfresco.web.ui.common.Utils; - -/** - * UI action command processor implementation. - *

- * Responsible for executing specific UI actions via a REST style URL interface. - *

- * The URL postfix for each specific command depends on the context that is required - * for that command. For example, a command to launch the Create Web Content dialog may - * require the current sandbox and the current web project as its context e.g. - *
- * http://server/alfresco/command/ui/createwebcontent?sandbox=website1&webproject=1234567890 - * - * @author Kevin Roast - */ -public class UIActionCommandProcessor implements ExtCommandProcessor -{ - private static final String MANAGE_TASK = "managetask"; - - public static final String PARAM_CONTAINER = "container"; - - private ServletContext sc = null; - private String command = null; - private Map args = null; - - static - { - // add our commands to the command registry - CommandFactory.getInstance().registerCommand(MANAGE_TASK, ManageTaskDialogCommand.class); - CommandFactory.getInstance().registerCommand("editcontentprops", EditContentPropertiesCommand.class); - CommandFactory.getInstance().registerCommand("userprofile", UserProfileDialogCommand.class); - CommandFactory.getInstance().registerCommand("editspace", EditSpaceCommand.class); - } - - - /** - * @see org.alfresco.web.app.servlet.command.CommandProcessor#validateArguments(javax.servlet.ServletContext, java.lang.String, java.util.Map, java.lang.String[]) - */ - public boolean validateArguments(ServletContext sc, String command, Map args, String[] urlElements) - { - this.sc = sc; - if (args.size() != 0) - { - this.args = new HashMap(args); - } - if (MANAGE_TASK.equals(command)) - { - String taskId = args.get(ManageTaskDialogCommand.PROP_TASKID); - return WorkflowUtil.isTaskEditable(taskId, sc); - } - return true; - } - - public void process(ServiceRegistry serviceRegistry, HttpServletRequest request, String command) - { - // not implemented in ExtCommandProcessor! - } - - /** - * @see org.alfresco.web.app.servlet.command.ExtCommandProcessor#process(org.alfresco.service.ServiceRegistry, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - public void process(ServiceRegistry serviceRegistry, HttpServletRequest request, HttpServletResponse response, String command) - { - Map properties = new HashMap(this.args); - - properties.put(BaseUIActionCommand.PROP_SERVLETCONTEXT, this.sc); - properties.put(BaseUIActionCommand.PROP_REQUEST, request); - properties.put(BaseUIActionCommand.PROP_RESPONSE, response); - - // if the container parameter is present and equal to "plain" add the - // external container object to the session - String container = request.getParameter(PARAM_CONTAINER); - if (container != null && container.equalsIgnoreCase("plain")) - { - request.getSession().setAttribute( - AlfrescoNavigationHandler.EXTERNAL_CONTAINER_SESSION, Boolean.TRUE); - } - - Command cmd = CommandFactory.getInstance().createCommand(command); - if (cmd == null) - { - throw new AlfrescoRuntimeException("Unregistered UI Action command specified: " + command); - } - cmd.execute(serviceRegistry, properties); - this.command = command; - } - - /** - * @see org.alfresco.web.app.servlet.command.CommandProcessor#outputStatus(java.io.PrintWriter) - */ - public void outputStatus(PrintWriter out) - { - out.print("UI Action command: '"); - out.print(Utils.encode(this.command)); - out.print("' executed with args: "); - out.println(this.args != null ? (Utils.encode(this.args.toString())) : ""); - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/command/UserProfileDialogCommand.java b/war/src/main/java/org/alfresco/web/app/servlet/command/UserProfileDialogCommand.java deleted file mode 100644 index a3788bafe2..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/command/UserProfileDialogCommand.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.command; - -import java.util.Map; - -import javax.faces.application.NavigationHandler; -import javax.faces.context.FacesContext; -import javax.servlet.ServletContext; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.service.ServiceRegistry; -import org.springframework.extensions.surf.util.ParameterCheck; -import org.alfresco.web.app.servlet.BaseServlet; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.users.UsersDialog; - -/** - * Command to execute the User Profile dialog via url. - *

- * Arguments: id = of the Person to display the User Profile for. - * - * @author Kevin Roast - */ -public class UserProfileDialogCommand extends BaseUIActionCommand -{ - public static final String PROP_PERSONID = "id"; - - private static final String[] PROPERTIES = new String[] { - PROP_SERVLETCONTEXT, PROP_REQUEST, PROP_RESPONSE, PROP_PERSONID}; - - /** - * @see org.alfresco.web.app.servlet.command.Command#execute(org.alfresco.service.ServiceRegistry, java.util.Map) - */ - public Object execute(ServiceRegistry serviceRegistry, Map properties) - { - ServletContext sc = (ServletContext)properties.get(PROP_SERVLETCONTEXT); - ServletRequest req = (ServletRequest)properties.get(PROP_REQUEST); - ServletResponse res = (ServletResponse)properties.get(PROP_RESPONSE); - FacesContext fc = FacesHelper.getFacesContext(req, res, sc, "/jsp/close.jsp"); - UsersDialog dialog = (UsersDialog)FacesHelper.getManagedBean(fc, UsersDialog.BEAN_NAME); - - // setup dialog context from url args in properties map - String personId = (String)properties.get(PROP_PERSONID); - ParameterCheck.mandatoryString(PROP_PERSONID, personId); - - dialog.setupUserAction(personId); - - NavigationHandler navigationHandler = fc.getApplication().getNavigationHandler(); - navigationHandler.handleNavigation(fc, null, "dialog:userProfile"); - String viewId = fc.getViewRoot().getViewId(); - try - { - sc.getRequestDispatcher(BaseServlet.FACES_SERVLET + viewId).forward(req, res); - } - catch (Exception e) - { - throw new AlfrescoRuntimeException("Unable to forward to viewId: " + viewId, e); - } - - return null; - } - - /** - * @see org.alfresco.web.app.servlet.command.Command#getPropertyNames() - */ - public String[] getPropertyNames() - { - return PROPERTIES; - } -} diff --git a/war/src/main/java/org/alfresco/web/app/servlet/command/WorkflowCommandProcessor.java b/war/src/main/java/org/alfresco/web/app/servlet/command/WorkflowCommandProcessor.java deleted file mode 100644 index 345e7a4c28..0000000000 --- a/war/src/main/java/org/alfresco/web/app/servlet/command/WorkflowCommandProcessor.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.app.servlet.command; - -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.web.ui.common.Utils; - -/** - * Workflow specific command processor implementation. - *

- * Responsible for executing 'approve' and 'reject' workflow commands on a Node. - * - * @author Kevin Roast - */ -public final class WorkflowCommandProcessor extends BaseNodeCommandProcessor -{ - private String command; - - static - { - // add our commands to the command registry - CommandFactory.getInstance().registerCommand("approve", ApproveWorkflowCommand.class); - CommandFactory.getInstance().registerCommand("reject", RejectWorkflowCommand.class); - } - - /** - * @see org.alfresco.web.app.servlet.command.CommandProcessor#process(org.alfresco.service.ServiceRegistry, javax.servlet.http.HttpServletRequest, java.lang.String) - */ - public void process(ServiceRegistry serviceRegistry, HttpServletRequest request, String command) - { - Map properties = new HashMap(1, 1.0f); - // all workflow commands use a "target" Node property as an argument - properties.put(ApproveWorkflowCommand.PROP_TARGET, this.targetRef); - Command cmd = CommandFactory.getInstance().createCommand(command); - if (cmd == null) - { - throw new AlfrescoRuntimeException("Unregistered workflow command specified: " + command); - } - cmd.execute(serviceRegistry, properties); - - this.command = command; - } - - /** - * @see org.alfresco.web.app.servlet.command.CommandProcessor#outputStatus(java.io.PrintWriter) - */ - public void outputStatus(PrintWriter out) - { - out.print("Workflow command: '"); - out.print(Utils.encode(this.command)); - out.print("' executed against node: "); - out.println(Utils.encode(this.targetRef.toString())); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/AboutBean.java b/war/src/main/java/org/alfresco/web/bean/AboutBean.java deleted file mode 100644 index 45d9890e3f..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/AboutBean.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean; - -import javax.faces.context.FacesContext; - -import org.alfresco.service.descriptor.DescriptorService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Repository; - -/** - * Simple backing bean used by the about page to display the version. - * - * @author gavinc - */ -public class AboutBean extends BaseDialogBean -{ - private static final long serialVersionUID = -3777479360531145878L; - - private final static String MSG_VERSION = "version"; - private final static String MSG_CLOSE = "close"; - - transient private DescriptorService descriptorService; - - /** - * Retrieves the version of the repository. - * - * @return The version string - */ - public String getVersion() - { - return this.getDescriptorService().getServerDescriptor().getVersion(); - } - - /** - * Retrieves the edition of the repository. - * - * @return The edition - */ - public String getEdition() - { - return this.getDescriptorService().getServerDescriptor().getEdition(); - } - - /** - * Sets the DescriptorService. - * - * @param descriptorService The DescriptorService - */ - public void setDescriptorService(DescriptorService descriptorService) - { - this.descriptorService = descriptorService; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - @Override - public String getContainerDescription() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_VERSION) + " :" + getEdition() + " - v" + getVersion(); - } - - DescriptorService getDescriptorService() - { - //check for null in cluster environment - if (descriptorService == null) - { - descriptorService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getDescriptorService(); - } - return descriptorService; - } - - @Override - public String getCancelButtonLabel() - { - - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } - - @Override - protected String getDefaultCancelOutcome() - { - return "dialog:close:browse"; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/BaseDetailsBean.java b/war/src/main/java/org/alfresco/web/bean/BaseDetailsBean.java deleted file mode 100644 index 031fad9512..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/BaseDetailsBean.java +++ /dev/null @@ -1,753 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.HashMap; -import java.util.Map; - -import javax.faces.application.FacesMessage; -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.transaction.RetryingTransactionHelper; -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.repo.web.scripts.FileTypeImageUtils; -import org.alfresco.service.cmr.repository.CopyService; -import org.alfresco.service.cmr.repository.FileTypeImageSize; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.TemplateImageResolver; -import org.alfresco.service.cmr.security.AccessStatus; -import org.alfresco.service.cmr.security.OwnableService; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.bean.actions.handlers.SimpleWorkflowHandler; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.workflow.WorkflowUtil; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.Utils.URLMode; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.alfresco.web.ui.common.component.UIPanel.ExpandedEvent; - -/** - * Backing bean provided access to the details of a Node - * - * @author Kevin Roast - */ -public abstract class BaseDetailsBean extends BaseDialogBean -{ - private static final String MSG_SUCCESS_OWNERSHIP = "success_ownership"; - - /** OwnableService bean reference */ - transient private OwnableService ownableService; - - /** CopyService bean reference */ - transient private CopyService copyService; - - /** The PermissionService reference */ - transient private PermissionService permissionService; - - /** Selected template Id */ - protected String template; - - /** The map of workflow properties */ - protected Map workflowProperties; - - protected Map panels = new HashMap(4, 1.0f); - - private static final String MSG_ERROR_WORKFLOW_REJECT = "error_workflow_reject"; - private static final String MSG_ERROR_WORKFLOW_APPROVE = "error_workflow_approve"; - private static final String MSG_ERROR_UPDATE_SIMPLEWORKFLOW = "error_update_simpleworkflow"; - - public BaseDetailsBean() - { - // initial state of some panels that don't use the default - panels.put("workflow-panel", false); - panels.put("category-panel", false); - } - - // ------------------------------------------------------------------------------ - // Bean property getters and setters - - /** - * Sets the ownable service instance the bean should use - * - * @param ownableService The OwnableService - */ - public void setOwnableService(OwnableService ownableService) - { - this.ownableService = ownableService; - } - - protected OwnableService getOwnableService() - { - if (ownableService == null) - { - ownableService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getOwnableService(); - } - return ownableService; - } - - /** - * Sets the copy service instance the bean should use - * - * @param copyService The CopyService - */ - public void setCopyService(CopyService copyService) - { - this.copyService = copyService; - } - - protected CopyService getCopyService() - { - if (copyService == null) - { - copyService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getCopyService(); - } - return copyService; - } - - /** - * @param permissionService The PermissionService to set. - */ - public void setPermissionService(PermissionService permissionService) - { - this.permissionService = permissionService; - } - - protected PermissionService getPermissionService() - { - if (permissionService == null) - { - permissionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPermissionService(); - } - return permissionService; - } - - /** - * @return Returns the panels expanded state map. - */ - public Map getPanels() - { - return this.panels; - } - - /** - * @param panels The panels expanded state map. - */ - public void setPanels(Map panels) - { - this.panels = panels; - } - - /** - * Returns the Node this bean is currently representing - * - * @return The Node - */ - public abstract Node getNode(); - - /** - * Returns the id of the current node - * - * @return The id - */ - public String getId() - { - return getNode().getId(); - } - - /** - * Returns the name of the current node - * - * @return Name of the current - */ - public String getName() - { - return getNode().getName(); - } - - /** - * Return the Alfresco NodeRef URL for the current node - * - * @return the Alfresco NodeRef URL - */ - public String getNodeRefUrl() - { - return getNode().getNodeRef().toString(); - } - - /** - * Returns the WebDAV URL for the current node - * - * @return The WebDAV url - */ - public String getWebdavUrl() - { - Node node = getLinkResolvedNode(); - return Utils.generateURL(FacesContext.getCurrentInstance(), node, URLMode.WEBDAV); - } - - /** - * Returns the CIFS path for the current node - * - * @return The CIFS path - */ - public String getCifsPath() - { - Node node = getLinkResolvedNode(); - return Utils.generateURL(FacesContext.getCurrentInstance(), node, URLMode.CIFS); - } - - /** - * Returns the URL to access the details page for the current node - * - * @return The bookmark URL - */ - public String getBookmarkUrl() - { - return Utils.generateURL(FacesContext.getCurrentInstance(), getNode(), URLMode.SHOW_DETAILS); - } - - /** - * Resolve the actual Node from any Link object that may be proxying it - * - * @return current Node or Node resolved from any Link object - */ - protected abstract Node getLinkResolvedNode(); - - /** - * @return Returns the template Id. - */ - public String getTemplate() - { - // return current template if it exists - NodeRef ref = (NodeRef)getNode().getProperties().get(ContentModel.PROP_TEMPLATE); - return ref != null ? ref.getId() : this.template; - } - - /** - * @param template The template Id to set. - */ - public void setTemplate(String template) - { - this.template = template; - } - - /** - * @return true if the current node has a custom Template or Webscript view applied and - * references a template/webscript that currently exists in the system. - */ - public boolean getHasCustomView() - { - return getHasWebscriptView() || getHasTemplateView(); - } - - /** - * @return true if the current node has a Template based custom view available - */ - public boolean getHasTemplateView() - { - if (getNode().hasAspect(ContentModel.ASPECT_TEMPLATABLE)) - { - NodeRef templateRef = (NodeRef)getNode().getProperties().get(ContentModel.PROP_TEMPLATE); - return (templateRef != null && this.getNodeService().exists(templateRef) && - this.getPermissionService().hasPermission(templateRef, PermissionService.READ) == AccessStatus.ALLOWED); - } - return false; - } - - /** - * @return true if the current node has a Webscript based custom view available - */ - public boolean getHasWebscriptView() - { - if (getNode().hasAspect(ContentModel.ASPECT_WEBSCRIPTABLE)) - { - return (getNode().getProperties().get(ContentModel.PROP_WEBSCRIPT) != null); - } - return false; - } - - /** - * @return String of the NodeRef for the custom view for the node - */ - public String getTemplateRef() - { - NodeRef ref = (NodeRef)getNode().getProperties().get(ContentModel.PROP_TEMPLATE); - return ref != null ? ref.toString() : null; - } - - /** - * @return Webscript URL for the custom view for the node - */ - public String getWebscriptUrl() - { - return (String)getNode().getProperties().get(ContentModel.PROP_WEBSCRIPT); - } - - /** - * Returns a model for use by a template on the Details page. - * - * @return model containing current current node info. - */ - public abstract Map getTemplateModel(); - - /** Template Image resolver helper */ - protected TemplateImageResolver imageResolver = new TemplateImageResolver() - { - private static final long serialVersionUID = 1539708282743314697L; - - public String resolveImagePathForName(String filename, FileTypeImageSize size) - { - return FileTypeImageUtils.getFileTypeImage(FacesContext.getCurrentInstance(), filename, size); - } - }; - - /** - * Returns the properties for the attached workflow as a map - * - * @return Properties of the attached workflow, null if there is no workflow - */ - public Map getWorkflowProperties() - { - if (this.workflowProperties == null && - getNode().hasAspect(ApplicationModel.ASPECT_SIMPLE_WORKFLOW)) - { - // get the exisiting properties for the node - Map props = getNode().getProperties(); - - String approveStepName = (String)props.get( - ApplicationModel.PROP_APPROVE_STEP.toString()); - String rejectStepName = (String)props.get( - ApplicationModel.PROP_REJECT_STEP.toString()); - - Boolean approveMove = (Boolean)props.get( - ApplicationModel.PROP_APPROVE_MOVE.toString()); - Boolean rejectMove = (Boolean)props.get( - ApplicationModel.PROP_REJECT_MOVE.toString()); - - NodeRef approveFolder = (NodeRef)props.get( - ApplicationModel.PROP_APPROVE_FOLDER.toString()); - NodeRef rejectFolder = (NodeRef)props.get( - ApplicationModel.PROP_REJECT_FOLDER.toString()); - - // put the workflow properties in a separate map for use by the JSP - this.workflowProperties = new HashMap(7); - this.workflowProperties.put(SimpleWorkflowHandler.PROP_APPROVE_STEP_NAME, - approveStepName); - this.workflowProperties.put(SimpleWorkflowHandler.PROP_APPROVE_ACTION, - approveMove ? "move" : "copy"); - this.workflowProperties.put(SimpleWorkflowHandler.PROP_APPROVE_FOLDER, approveFolder); - - if (rejectStepName == null || rejectMove == null || rejectFolder == null) - { - this.workflowProperties.put(SimpleWorkflowHandler.PROP_REJECT_STEP_PRESENT, "no"); - } - else - { - this.workflowProperties.put(SimpleWorkflowHandler.PROP_REJECT_STEP_PRESENT, - "yes"); - this.workflowProperties.put(SimpleWorkflowHandler.PROP_REJECT_STEP_NAME, - rejectStepName); - this.workflowProperties.put(SimpleWorkflowHandler.PROP_REJECT_ACTION, - rejectMove ? "move" : "copy"); - this.workflowProperties.put(SimpleWorkflowHandler.PROP_REJECT_FOLDER, - rejectFolder); - } - } - - return this.workflowProperties; - } - - /** - * Cancel Workflow Edit dialog - */ - public String cancelWorkflowEdit() - { - // resets the workflow properties map so any changes made - // don't appear to be persisted - this.workflowProperties.clear(); - this.workflowProperties = null; - return "cancel"; - } - - /** - * Saves the details of the workflow stored in workflowProperties - * to the current node - * - * @return The outcome string - */ - public String saveWorkflow() - { - String outcome = "cancel"; - - try - { - RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(FacesContext.getCurrentInstance()); - RetryingTransactionCallback callback = new RetryingTransactionCallback() - { - public Object execute() throws Throwable - { - // firstly retrieve all the properties for the current node - Map updateProps = getNodeService().getProperties( - getNode().getNodeRef()); - - // update the simple workflow properties - - // set the approve step name - updateProps.put(ApplicationModel.PROP_APPROVE_STEP, - workflowProperties.get(SimpleWorkflowHandler.PROP_APPROVE_STEP_NAME)); - - // specify whether the approve step will copy or move the content - boolean approveMove = true; - String approveAction = (String)workflowProperties.get(SimpleWorkflowHandler.PROP_APPROVE_ACTION); - if (approveAction != null && approveAction.equals("copy")) - { - approveMove = false; - } - updateProps.put(ApplicationModel.PROP_APPROVE_MOVE, Boolean.valueOf(approveMove)); - - // create node ref representation of the destination folder - updateProps.put(ApplicationModel.PROP_APPROVE_FOLDER, - workflowProperties.get(SimpleWorkflowHandler.PROP_APPROVE_FOLDER)); - - // determine whether there should be a reject step - boolean requireReject = true; - String rejectStepPresent = (String)workflowProperties.get( - SimpleWorkflowHandler.PROP_REJECT_STEP_PRESENT); - if (rejectStepPresent != null && rejectStepPresent.equals("no")) - { - requireReject = false; - } - - if (requireReject) - { - // set the reject step name - updateProps.put(ApplicationModel.PROP_REJECT_STEP, - workflowProperties.get(SimpleWorkflowHandler.PROP_REJECT_STEP_NAME)); - - // specify whether the reject step will copy or move the content - boolean rejectMove = true; - String rejectAction = (String)workflowProperties.get( - SimpleWorkflowHandler.PROP_REJECT_ACTION); - if (rejectAction != null && rejectAction.equals("copy")) - { - rejectMove = false; - } - updateProps.put(ApplicationModel.PROP_REJECT_MOVE, Boolean.valueOf(rejectMove)); - - // create node ref representation of the destination folder - updateProps.put(ApplicationModel.PROP_REJECT_FOLDER, - workflowProperties.get(SimpleWorkflowHandler.PROP_REJECT_FOLDER)); - } - else - { - // set all the reject properties to null to signify there should - // be no reject step - updateProps.put(ApplicationModel.PROP_REJECT_STEP, null); - updateProps.put(ApplicationModel.PROP_REJECT_MOVE, null); - updateProps.put(ApplicationModel.PROP_REJECT_FOLDER, null); - } - - // set the properties on the node - getNodeService().setProperties(getNode().getNodeRef(), updateProps); - return null; - } - }; - txnHelper.doInTransaction(callback); - - // reset the state of the current node so it reflects the changes just made - getNode().reset(); - - outcome = "finish"; - } - catch (Throwable e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), MSG_ERROR_UPDATE_SIMPLEWORKFLOW), e.getMessage()), e); - ReportedException.throwIfNecessary(e); - } - - return outcome; - } - - /** - * Returns the name of the approve step of the attached workflow - * - * @return The name of the approve step or null if there is no workflow - */ - public String getApproveStepName() - { - String approveStepName = null; - - if (getNode().hasAspect(ApplicationModel.ASPECT_SIMPLE_WORKFLOW)) - { - approveStepName = (String)getNode().getProperties().get( - ApplicationModel.PROP_APPROVE_STEP.toString()); - } - - return approveStepName; - } - - /** - * Event handler called to handle the approve step of the simple workflow - * - * @param event The event that was triggered - */ - public void approve(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id == null || id.length() == 0) - { - throw new AlfrescoRuntimeException("approve called without an id"); - } - - final NodeRef docNodeRef = new NodeRef(Repository.getStoreRef(), id); - - try - { - RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(FacesContext.getCurrentInstance()); - RetryingTransactionCallback callback = new RetryingTransactionCallback() - { - public Object execute() throws Throwable - { - // call the service to perform the approve - WorkflowUtil.approve(docNodeRef, getNodeService(), getCopyService()); - return null; - } - }; - txnHelper.doInTransaction(callback); - - // if this was called via the node details dialog we need to reset the node - if (getNode() != null) - { - getNode().reset(); - } - - // also make sure the UI will get refreshed - UIContextService.getInstance(FacesContext.getCurrentInstance()).notifyBeans(); - } - catch (Throwable e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), MSG_ERROR_WORKFLOW_APPROVE), e.getMessage()), e); - ReportedException.throwIfNecessary(e); - } - } - - /** - * Returns the name of the reject step of the attached workflow - * - * @return The name of the reject step or null if there is no workflow - */ - public String getRejectStepName() - { - String approveStepName = null; - - if (getNode().hasAspect(ApplicationModel.ASPECT_SIMPLE_WORKFLOW)) - { - approveStepName = (String)getNode().getProperties().get( - ApplicationModel.PROP_REJECT_STEP.toString()); - } - - return approveStepName; - } - - /** - * Event handler called to handle the approve step of the simple workflow - * - * @param event The event that was triggered - */ - public void reject(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id == null || id.length() == 0) - { - throw new AlfrescoRuntimeException("reject called without an id"); - } - - final NodeRef docNodeRef = new NodeRef(Repository.getStoreRef(), id); - - try - { - RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(FacesContext.getCurrentInstance()); - RetryingTransactionCallback callback = new RetryingTransactionCallback() - { - public Object execute() throws Throwable - { - // call the service to perform the reject - WorkflowUtil.reject(docNodeRef, getNodeService(), getCopyService()); - return null; - } - }; - txnHelper.doInTransaction(callback); - - // if this was called via the node details dialog we need to reset the node - if (getNode() != null) - { - getNode().reset(); - } - - // also make sure the UI will get refreshed - UIContextService.getInstance(FacesContext.getCurrentInstance()).notifyBeans(); - } - catch (Throwable e) - { - // rollback the transaction - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), MSG_ERROR_WORKFLOW_REJECT), e.getMessage()), e); - ReportedException.throwIfNecessary(e); - } - } - - // ------------------------------------------------------------------------------ - // Action event handlers - - /** - * Action handler to apply the selected Template and Templatable aspect to the current node - */ - public void applyTemplate(ActionEvent event) - { - if (this.template != null && this.template.equals(TemplateSupportBean.NO_SELECTION) == false) - { - try - { - // apply the templatable aspect if required - if (getNode().hasAspect(ContentModel.ASPECT_TEMPLATABLE) == false) - { - this.getNodeService().addAspect(getNode().getNodeRef(), ContentModel.ASPECT_TEMPLATABLE, null); - } - - // get the selected template from the Template Picker - NodeRef templateRef = new NodeRef(Repository.getStoreRef(), this.template); - - // set the template NodeRef into the templatable aspect property - this.getNodeService().setProperty(getNode().getNodeRef(), ContentModel.PROP_TEMPLATE, templateRef); - - // reset node details for next refresh of details page - getNode().reset(); - } - catch (Exception e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), e.getMessage()), e); - } - } - } - - /** - * Action handler to remove a custom view template from the current node - */ - public void removeTemplate(ActionEvent event) - { - try - { - // clear template property - this.getNodeService().setProperty(getNode().getNodeRef(), ContentModel.PROP_TEMPLATE, null); - this.getNodeService().removeAspect(getNode().getNodeRef(), ContentModel.ASPECT_TEMPLATABLE); - this.getNodeService().removeAspect(getNode().getNodeRef(), ContentModel.ASPECT_WEBSCRIPTABLE); - - // reset node details for next refresh of details page - getNode().reset(); - } - catch (Exception e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), e.getMessage()), e); - } - } - - /** - * Action Handler to take Ownership of the current node - */ - public void takeOwnership(final ActionEvent event) - { - final FacesContext fc = FacesContext.getCurrentInstance(); - - try - { - RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(FacesContext.getCurrentInstance()); - RetryingTransactionCallback callback = new RetryingTransactionCallback() - { - public Object execute() throws Throwable - { - getOwnableService().takeOwnership(getNode().getNodeRef()); - - String msg = Application.getMessage(fc, MSG_SUCCESS_OWNERSHIP); - FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg); - String formId = Utils.getParentForm(fc, event.getComponent()).getClientId(fc); - fc.addMessage(formId + ':' + getPropertiesPanelId(), facesMsg); - - getNode().reset(); - return null; - } - }; - txnHelper.doInTransaction(callback); - } - catch (Throwable e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - fc, Repository.ERROR_GENERIC), e.getMessage()), e); - ReportedException.throwIfNecessary(e); - } - } - - /** - * @return id of the properties panel component - */ - protected abstract String getPropertiesPanelId(); - - /** - * Save the state of the panel that was expanded/collapsed - */ - public void expandPanel(ActionEvent event) - { - if (event instanceof ExpandedEvent) - { - String id = event.getComponent().getId(); - // we prefix some panels with "no-" which we remove to give consistent behaviour in the UI - if (id.startsWith("no-") == true) - { - id = id.substring(3); - } - this.panels.put(id, ((ExpandedEvent)event).State); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/BrowseBean.java b/war/src/main/java/org/alfresco/web/bean/BrowseBean.java deleted file mode 100644 index 4e017cfa4e..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/BrowseBean.java +++ /dev/null @@ -1,2450 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean; - -import java.io.IOException; -import java.io.Serializable; -import java.io.StringWriter; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import javax.faces.context.FacesContext; -import javax.faces.event.AbortProcessingException; -import javax.faces.event.ActionEvent; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.search.SearcherException; -import org.alfresco.repo.site.SiteModel; -import org.alfresco.repo.web.scripts.FileTypeImageUtils; -import org.alfresco.service.cmr.coci.CheckOutCheckInService; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.dictionary.TypeDefinition; -import org.alfresco.service.cmr.lock.LockService; -import org.alfresco.service.cmr.ml.MultilingualContentService; -import org.alfresco.service.cmr.model.FileFolderService; -import org.alfresco.service.cmr.model.FileInfo; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.ContentData; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.search.LimitBy; -import org.alfresco.service.cmr.search.ResultSet; -import org.alfresco.service.cmr.search.ResultSetRow; -import org.alfresco.service.cmr.search.SearchParameters; -import org.alfresco.service.cmr.search.SearchService; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.namespace.QName; -import org.alfresco.service.namespace.RegexQNamePattern; -import org.alfresco.util.FileFilterMode; -import org.alfresco.util.FileFilterMode.Client; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.IContextListener; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.app.servlet.DownloadContentServlet; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.content.DocumentDetailsDialog; -import org.alfresco.web.bean.ml.MultilingualManageDialog; -import org.alfresco.web.bean.repository.MapNode; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.NodePropertyResolver; -import org.alfresco.web.bean.repository.QNameNodeMap; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.search.SearchContext; -import org.alfresco.web.bean.spaces.CreateSpaceWizard; -import org.alfresco.web.bean.users.UserPreferencesBean; -import org.alfresco.web.config.ClientConfigElement; -import org.alfresco.web.config.ViewsConfigElement; -import org.alfresco.web.ui.common.PanelGenerator; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.Utils.URLMode; -import org.alfresco.web.ui.common.component.IBreadcrumbHandler; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.alfresco.web.ui.common.component.UIBreadcrumb; -import org.alfresco.web.ui.common.component.UIModeList; -import org.alfresco.web.ui.common.component.UIPanel.ExpandedEvent; -import org.alfresco.web.ui.common.component.UIStatusMessage; -import org.alfresco.web.ui.common.component.data.UIRichList; -import org.alfresco.web.ui.repo.component.IRepoBreadcrumbHandler; -import org.alfresco.web.ui.repo.component.UINodeDescendants; -import org.alfresco.web.ui.repo.component.UINodePath; -import org.alfresco.web.ui.repo.component.UISimpleSearch; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.extensions.config.Config; -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigService; - - -/** - * Bean providing properties and behaviour for the main folder/document browse screen and - * search results screens. - * - * @author Kevin Roast - */ -public class BrowseBean implements IContextListener, Serializable -{ - private static final long serialVersionUID = -3234262484615161360L; - - /** Public JSF Bean name */ - public static final String BEAN_NAME = "BrowseBean"; - - - // ------------------------------------------------------------------------------ - // Construction - - /** - * Default Constructor - */ - public BrowseBean() - { - UIContextService.getInstance(FacesContext.getCurrentInstance()).registerBean(this); - - initFromClientConfig(); - } - - - // ------------------------------------------------------------------------------ - // Bean property getters and setters - - /** - * @param nodeService The NodeService to set. - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - protected NodeService getNodeService() - { - if (nodeService == null) - { - nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - } - return nodeService; - } - - /** - * @param checkOutCheckInService The service for check-in and check-out. - */ - public void setCheckOutCheckInService(CheckOutCheckInService checkOutCheckInService) - { - this.checkOutCheckInService = checkOutCheckInService; - } - - protected CheckOutCheckInService getCheckOutCheckInService() - { - if (checkOutCheckInService == null) - { - checkOutCheckInService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getCheckOutCheckInService(); - } - return checkOutCheckInService; - } - - /** - * @param searchService The Searcher to set. - */ - public void setSearchService(SearchService searchService) - { - this.searchService = searchService; - } - - protected SearchService getSearchService() - { - if (searchService == null) - { - searchService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getSearchService(); - } - return searchService; - } - - /** - * @param userPreferencesBean The UserPreferencesBean to set. - */ - public void setUserPreferencesBean(UserPreferencesBean userPreferencesBean) - { - this.userPreferencesBean = userPreferencesBean; - } - - /** - * @param lockService The Lock Service to set. - */ - public void setLockService(LockService lockService) - { - this.lockService = lockService; - } - - protected LockService getLockService() - { - if (lockService == null) - { - lockService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getLockService(); - } - return lockService; - } - - /** - * @param navigator The NavigationBean to set. - */ - public void setNavigator(NavigationBean navigator) - { - this.navigator = navigator; - } - - /** - * @param dictionaryService The DictionaryService to set. - */ - public void setDictionaryService(DictionaryService dictionaryService) - { - this.dictionaryService = dictionaryService; - } - - protected DictionaryService getDictionaryService() - { - if (dictionaryService == null) - { - dictionaryService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getDictionaryService(); - } - return dictionaryService; - } - - /** - * @param multilingualContentService The Multilingual Content Service to set. - */ - public void setMultilingualContentService(MultilingualContentService multilingualContentService) - { - this.multilingualContentService = multilingualContentService; - } - - protected MultilingualContentService getMultilingualContentService() - { - if (multilingualContentService == null) - { - multilingualContentService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getMultilingualContentService(); - } - return multilingualContentService; - } - - /** - * @param fileFolderService The FileFolderService to set. - */ - public void setFileFolderService(FileFolderService fileFolderService) - { - this.fileFolderService = fileFolderService; - } - - protected FileFolderService getFileFolderService() - { - if (fileFolderService == null) - { - fileFolderService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getFileFolderService(); - } - return fileFolderService; - } - - /** - * @return Returns the browse View mode. See UIRichList - */ - public String getBrowseViewMode() - { - return this.browseViewMode; - } - - /** - * @param browseViewMode The browse View mode to set. See UIRichList. - */ - public void setBrowseViewMode(String browseViewMode) - { - this.browseViewMode = browseViewMode; - } - - /** - * @return Returns true if dashboard view is available for the current node. - */ - public boolean isDashboardView() - { - return this.dashboardView; - } - - /** - * @param dashboardView The dashboard view mode to set. - */ - public void setDashboardView(boolean dashboardView) - { - this.dashboardView = dashboardView; - if (dashboardView == true) - { - FacesContext fc = FacesContext.getCurrentInstance(); - fc.getApplication().getNavigationHandler().handleNavigation(fc, null, "dashboard"); - } - } - - public int getPageSizeContent() - { - return this.pageSizeContent; - } - - public void setPageSizeContent(int pageSizeContent) - { - this.pageSizeContent = pageSizeContent; - this.pageSizeContentStr = Integer.toString(pageSizeContent); - } - - public int getPageSizeSpaces() - { - return this.pageSizeSpaces; - } - - public void setPageSizeSpaces(int pageSizeSpaces) - { - this.pageSizeSpaces = pageSizeSpaces; - this.pageSizeSpacesStr = Integer.toString(pageSizeSpaces); - } - - public String getPageSizeContentStr() - { - return this.pageSizeContentStr; - } - - public void setPageSizeContentStr(String pageSizeContentStr) - { - this.pageSizeContentStr = pageSizeContentStr; - } - - public String getPageSizeSpacesStr() - { - return this.pageSizeSpacesStr; - } - - public void setPageSizeSpacesStr(String pageSizeSpacesStr) - { - this.pageSizeSpacesStr = pageSizeSpacesStr; - } - - /** - * @return Returns the minimum length of a valid search string. - */ - public static int getMinimumSearchLength() - { - return Application.getClientConfig(FacesContext.getCurrentInstance()).getSearchMinimum(); - } - - /** - * @return Returns the panels expanded state map. - */ - public Map getPanels() - { - return this.panels; - } - - /** - * @param panels The panels expanded state map. - */ - public void setPanels(Map panels) - { - this.panels = panels; - } - - /** - * @return Returns the Space Node being used for the current browse screen action. - */ - public Node getActionSpace() - { - return this.actionSpace; - } - - /** - * @param actionSpace Set the Space Node to be used for the current browse screen action. - */ - public void setActionSpace(Node actionSpace) - { - if (actionSpace != null) - { - for (NodeEventListener listener : getNodeEventListeners()) - { - listener.created(actionSpace, actionSpace.getType()); - } - } - this.actionSpace = actionSpace; - } - - /** - * @return The document node being used for the current operation - */ - public Node getDocument() - { - return this.document; - } - - /** - * @param document The document node to be used for the current operation - */ - public void setDocument(Node document) - { - if (document != null) - { - for (NodeEventListener listener : getNodeEventListeners()) - { - listener.created(document, document.getType()); - } - } - this.document = document; - } - - /** - * @param contentRichList The contentRichList to set. - */ - public void setContentRichList(UIRichList contentRichList) - { - this.contentRichList = contentRichList; - if (this.contentRichList != null) - { - this.contentRichList.setInitialSortColumn( - this.viewsConfig.getDefaultSortColumn(PAGE_NAME_BROWSE)); - this.contentRichList.setInitialSortDescending( - this.viewsConfig.hasDescendingSort(PAGE_NAME_BROWSE)); - } - // special case to handle an External Access URL - // these URLs restart the JSF lifecycle but an old UIRichList is restored from - // the component tree - which needs clearing "late" in the lifecycle process - if (externalForceRefresh) - { - this.contentRichList.setValue(null); - externalForceRefresh = false; - } - } - - /** - * @return Returns the contentRichList. - */ - public UIRichList getContentRichList() - { - return this.contentRichList; - } - - /** - * @param spacesRichList The spacesRichList to set. - */ - public void setSpacesRichList(UIRichList spacesRichList) - { - this.spacesRichList = spacesRichList; - if (this.spacesRichList != null) - { - // set the initial sort column and direction - this.spacesRichList.setInitialSortColumn( - this.viewsConfig.getDefaultSortColumn(PAGE_NAME_BROWSE)); - this.spacesRichList.setInitialSortDescending( - this.viewsConfig.hasDescendingSort(PAGE_NAME_BROWSE)); - } - if (externalForceRefresh) - { - this.spacesRichList.setValue(null); - } - } - - /** - * @return Returns the spacesRichList. - */ - public UIRichList getSpacesRichList() - { - return this.spacesRichList; - } - - /** - * @return Returns the statusMessage component. - */ - public UIStatusMessage getStatusMessage() - { - return this.statusMessage; - } - - /** - * @param statusMessage The statusMessage component to set. - */ - public void setStatusMessage(UIStatusMessage statusMessage) - { - this.statusMessage = statusMessage; - } - - /** - * @return Returns the deleteMessage. - */ - public String getDeleteMessage() - { - return this.deleteMessage; - } - - /** - * @param deleteMessage The deleteMessage to set. - */ - public void setDeleteMessage(String deleteMessage) - { - this.deleteMessage = deleteMessage; - } - - /** - * Page accessed bean method to get the container nodes currently being browsed - * - * @return List of container Node objects for the current browse location - */ - public List getNodes() - { - // the references to container nodes and content nodes are transient for one use only - // we do this so we only query/search once - as we cannot distinguish between node types - // until after the query. The logic is a bit confusing but otherwise we would need to - // perform the same query or search twice for every screen refresh. - if (this.containerNodes == null) - { - if (this.navigator.getSearchContext() == null) - { - queryBrowseNodes(this.navigator.getCurrentNodeId()); - } - else - { - searchBrowseNodes(this.navigator.getSearchContext()); - } - } - List result = this.containerNodes; - - // we clear the member variable during invalidateComponents() - - return result; - } - - /** - * Page accessed bean method to get the content nodes currently being browsed - * - * @return List of content Node objects for the current browse location - */ - public List getContent() - { - // see comment in getNodes() above for reasoning here - if (this.contentNodes == null) - { - if (this.navigator.getSearchContext() == null) - { - queryBrowseNodes(this.navigator.getCurrentNodeId()); - } - else - { - searchBrowseNodes(this.navigator.getSearchContext()); - } - } - List result = this.contentNodes; - - // we clear the member variable during invalidateComponents() - - return result; - } - - /** - * Page accessed bean method to get the parent container nodes currently being browsed - * - * @return List of parent container Node objects for the current browse location - */ - public List getParentNodes(NodeRef currNodeRef) - { - // As per AWC-1507 there are two scenarios for navigating to the space details. First - // scenario is to show space details of the current space. Second scenario is to show - // space details of a child space of the current space. For now, added an extra query - // so that existing context remains unaffected for second scenario, although it does - // mean that in first scenario there will be an extra query even though parentContainerNodes - // and containerNodes will contain the same list. - - if (this.parentContainerNodes == null) - { - long startTime = 0; - if (logger.isDebugEnabled()) - startTime = System.currentTimeMillis(); - - UserTransaction tx = null; - try - { - FacesContext context = FacesContext.getCurrentInstance(); - tx = Repository.getUserTransaction(context, true); - tx.begin(); - - NodeRef parentRef = getNodeService().getPrimaryParent(currNodeRef).getParentRef(); - - List children = this.getFileFolderService().list(parentRef); - this.parentContainerNodes = new ArrayList(children.size()); - for (FileInfo fileInfo : children) - { - // create our Node representation from the NodeRef - NodeRef nodeRef = fileInfo.getNodeRef(); - - // find it's type so we can see if it's a node we are interested in - QName type = this.getNodeService().getType(nodeRef); - - // make sure the type is defined in the data dictionary - TypeDefinition typeDef = this.getDictionaryService().getType(type); - - if (typeDef != null) - { - MapNode node = null; - - // look for Space folder node - if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_FOLDER) == true && - this.getDictionaryService().isSubClass(type, ContentModel.TYPE_SYSTEM_FOLDER) == false) - { - // create our Node representation - node = new MapNode(nodeRef, this.getNodeService(), fileInfo.getProperties()); - node.addPropertyResolver("icon", this.resolverSpaceIcon); - node.addPropertyResolver("smallIcon", this.resolverSmallIcon); - - this.parentContainerNodes.add(node); - } - else if (ApplicationModel.TYPE_FOLDERLINK.equals(type)) - { - // create our Folder Link Node representation - node = new MapNode(nodeRef, this.getNodeService(), fileInfo.getProperties()); - node.addPropertyResolver("icon", this.resolverSpaceIcon); - node.addPropertyResolver("smallIcon", this.resolverSmallIcon); - - this.parentContainerNodes.add(node); - } - } - else - { - if (logger.isWarnEnabled()) - logger.warn("Found invalid object in database: id = " + nodeRef + ", type = " + type); - } - } - - // commit the transaction - tx.commit(); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {refErr.getNodeRef()}), refErr ); - this.parentContainerNodes = Collections.emptyList(); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err); - this.parentContainerNodes = Collections.emptyList(); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - - if (logger.isDebugEnabled()) - { - long endTime = System.currentTimeMillis(); - logger.debug("Time to query and build map parent nodes: " + (endTime - startTime) + "ms"); - } - } - - List result = this.parentContainerNodes; - - // we clear the member variable during invalidateComponents() - - return result; - } - - /** - * Determines whether the current space is a 'Sites' space - * - * @return true if the current space is a 'Sites' space - */ - public boolean isSitesSpace() - { - boolean siteSpace = false; - - Node currentNode = this.navigator.getCurrentNode(); - if (currentNode != null) - { - // check the type of the node to see if it is a 'site' related space - QName currentNodeType = currentNode.getType(); - - if (SiteModel.TYPE_SITES.isMatch(currentNodeType) || - SiteModel.TYPE_SITE.isMatch(currentNodeType) || - getDictionaryService().isSubClass(currentNodeType, SiteModel.TYPE_SITE)) - { - siteSpace = true; - } - } - - return siteSpace; - } - - /** - * Returns the HTML to display if a space is a 'Sites' space - * - * @return The HTML to display - */ - public String getSitesSpaceWarningHTML() - { - FacesContext context = FacesContext.getCurrentInstance(); - String contextPath = context.getExternalContext().getRequestContextPath(); - StringBuilder html = new StringBuilder(); - - try - { - html.append(""); - html.append(""); - - StringWriter writer = new StringWriter(); - PanelGenerator.generatePanelStart(writer, contextPath, "yellowInner", "#ffffcc"); - html.append(writer.toString()); - - html.append(""); - html.append(""); - html.append("
"); - html.append(""); - html.append(Application.getMessage(context, "sites_space_warning")); - html.append("
"); - - writer = new StringWriter(); - PanelGenerator.generatePanelEnd(writer, contextPath, "yellowInner"); - html.append(writer.toString()); - - html.append(""); - } - catch (IOException ioe) - { - logger.error(ioe); - } - - return html.toString(); - } - - /** - * Setup the common properties required at data-binding time. - *

- * These are properties used by components on the page when iterating over the nodes. - * The properties are available as the Node is a Map so they can be accessed directly - * by name. Information such as download URL, size and filetype are provided etc. - *

- * We use a set of anonymous inner classes to provide the implemention for the property - * getters. The interfaces are only called when the properties are first requested. - * - * @param node Node to add the properties too - */ - public void setupCommonBindingProperties(Node node) - { - // special properties to be used by the value binding components on the page - node.addPropertyResolver("url", this.resolverUrl); - - if (ApplicationModel.TYPE_FILELINK.equals(node.getType())) - { - node.addPropertyResolver("downloadUrl", this.resolverLinkDownload); - } - else - { - node.addPropertyResolver("downloadUrl", this.resolverDownload); - } - - node.addPropertyResolver("webdavUrl", this.resolverWebdavUrl); - node.addPropertyResolver("cifsPath", this.resolverCifsPath); - node.addPropertyResolver("fileType16", this.resolverFileType16); - node.addPropertyResolver("fileType32", this.resolverFileType32); - node.addPropertyResolver("size", this.resolverSize); - node.addPropertyResolver("lang", this.resolverLang); - } - - - // ------------------------------------------------------------------------------ - // IContextListener implementation - - /** - * @see org.alfresco.web.app.context.IContextListener#contextUpdated() - */ - public void contextUpdated() - { - invalidateComponents(); - } - - /** - * @see org.alfresco.web.app.context.IContextListener#areaChanged() - */ - public void areaChanged() - { - // nothing to do - } - - /** - * @see org.alfresco.web.app.context.IContextListener#spaceChanged() - */ - public void spaceChanged() - { - // nothing to do - } - - - // ------------------------------------------------------------------------------ - // NodeEventListener listeners - - /** - * Add a listener to those called by the BrowseBean when nodes are created - */ - public void addNodeEventListener(NodeEventListener listener) - { - if (this.nodeEventListeners == null) - { - this.nodeEventListeners = new HashSet(); - } - this.nodeEventListeners.add(listener); - } - - /** - * Remove a listener from the list of those called by BrowseBean - */ - public void removeNodeEventListener(NodeEventListener listener) - { - if (this.nodeEventListeners != null) - { - this.nodeEventListeners.remove(listener); - } - } - - - // ------------------------------------------------------------------------------ - // Navigation action event handlers - - /** - * Change the current view mode based on user selection - * - * @param event ActionEvent - */ - public void viewModeChanged(ActionEvent event) - { - UIModeList viewList = (UIModeList)event.getComponent(); - - // get the view mode ID - String viewMode = viewList.getValue().toString(); - - if (VIEWMODE_DASHBOARD.equals(viewMode) == false) - { - // set the page size based on the style of display - int pageSize = this.viewsConfig.getDefaultPageSize(PAGE_NAME_BROWSE, viewMode); - setPageSizeContent(pageSize); - setPageSizeSpaces(pageSize); - - if (logger.isDebugEnabled()) - logger.debug("Browse view page size set to: " + pageSize); - - setDashboardView(false); - - // push the view mode into the lists - setBrowseViewMode(viewMode); - - // setup dispatch context for custom views - this.navigator.setupDispatchContext(this.navigator.getCurrentNode()); - - // browse to appropriate view - FacesContext fc = FacesContext.getCurrentInstance(); - String outcome = null; - String viewId = fc.getViewRoot().getViewId(); - if (viewId.equals(BROWSE_VIEW_ID) == false && viewId.equals(CATEGORY_VIEW_ID) == false) - { - outcome = "browse"; - } - fc.getApplication().getNavigationHandler().handleNavigation(fc, null, outcome); - } - else - { - // special case for Dashboard view - setDashboardView(true); - } - } - - - // ------------------------------------------------------------------------------ - // Helper methods - - /** - * Query a list of nodes for the specified parent node Id - * - * @param parentNodeId Id of the parent node or null for the root node - */ - private void queryBrowseNodes(String parentNodeId) - { - long startTime = 0; - if (logger.isDebugEnabled()) - startTime = System.currentTimeMillis(); - - UserTransaction tx = null; - try - { - FacesContext context = FacesContext.getCurrentInstance(); - tx = Repository.getUserTransaction(context, true); - tx.begin(); - - NodeRef parentRef; - if (parentNodeId == null) - { - // no specific parent node specified - use the root node - parentRef = this.getNodeService().getRootNode(Repository.getStoreRef()); - } - else - { - // build a NodeRef for the specified Id and our store - parentRef = new NodeRef(Repository.getStoreRef(), parentNodeId); - } - - List children = null; - FileFilterMode.setClient(Client.webclient); - try - { - children = this.getFileFolderService().list(parentRef); - } - finally - { - FileFilterMode.clearClient(); - } - - this.containerNodes = new ArrayList(children.size()); - this.contentNodes = new ArrayList(children.size()); - - // in case of dynamic config, only lookup once - Set nodeEventListeners = getNodeEventListeners(); - - for (FileInfo fileInfo : children) - { - // create our Node representation from the NodeRef - NodeRef nodeRef = fileInfo.getNodeRef(); - - // find it's type so we can see if it's a node we are interested in - QName type = this.getNodeService().getType(nodeRef); - - // make sure the type is defined in the data dictionary - TypeDefinition typeDef = this.getDictionaryService().getType(type); - - if (typeDef != null) - { - MapNode node = null; - - // look for File content node - if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_CONTENT)) - { - // create our Node representation - node = new MapNode(nodeRef, this.getNodeService(), fileInfo.getProperties()); - setupCommonBindingProperties(node); - - this.contentNodes.add(node); - } - // look for Space folder node - else if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_FOLDER) == true && - this.getDictionaryService().isSubClass(type, ContentModel.TYPE_SYSTEM_FOLDER) == false) - { - // create our Node representation - node = new MapNode(nodeRef, this.getNodeService(), fileInfo.getProperties()); - node.addPropertyResolver("icon", this.resolverSpaceIcon); - node.addPropertyResolver("smallIcon", this.resolverSmallIcon); - - this.containerNodes.add(node); - } - // look for File Link object node - else if (ApplicationModel.TYPE_FILELINK.equals(type)) - { - // create our File Link Node representation - node = new MapNode(nodeRef, this.getNodeService(), fileInfo.getProperties()); - // only display the user has the permissions to navigate to the target of the link - NodeRef destRef = (NodeRef)node.getProperties().get(ContentModel.PROP_LINK_DESTINATION); - if (destRef != null && new Node(destRef).hasPermission(PermissionService.READ) == true) - { - node.addPropertyResolver("url", this.resolverLinkUrl); - node.addPropertyResolver("downloadUrl", this.resolverLinkDownload); - node.addPropertyResolver("webdavUrl", this.resolverLinkWebdavUrl); - node.addPropertyResolver("cifsPath", this.resolverLinkCifsPath); - node.addPropertyResolver("fileType16", this.resolverFileType16); - node.addPropertyResolver("fileType32", this.resolverFileType32); - node.addPropertyResolver("lang", this.resolverLang); - - this.contentNodes.add(node); - } - } - else if (ApplicationModel.TYPE_FOLDERLINK.equals(type)) - { - // create our Folder Link Node representation - node = new MapNode(nodeRef, this.getNodeService(), fileInfo.getProperties()); - // only display the user has the permissions to navigate to the target of the link - NodeRef destRef = (NodeRef)node.getProperties().get(ContentModel.PROP_LINK_DESTINATION); - if (destRef != null && new Node(destRef).hasPermission(PermissionService.READ) == true) - { - node.addPropertyResolver("icon", this.resolverSpaceIcon); - node.addPropertyResolver("smallIcon", this.resolverSmallIcon); - - this.containerNodes.add(node); - } - } - - // inform any listeners that a Node wrapper has been created - if (node != null) - { - for (NodeEventListener listener : nodeEventListeners) - { - listener.created(node, type); - } - } - } - else - { - if (logger.isWarnEnabled()) - logger.warn("Found invalid object in database: id = " + nodeRef + ", type = " + type); - } - } - - // commit the transaction - tx.commit(); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {refErr.getNodeRef()}), refErr ); - this.containerNodes = Collections.emptyList(); - this.contentNodes = Collections.emptyList(); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err); - this.containerNodes = Collections.emptyList(); - this.contentNodes = Collections.emptyList(); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - - if (logger.isDebugEnabled()) - { - long endTime = System.currentTimeMillis(); - logger.debug("Time to query and build map nodes: " + (endTime - startTime) + "ms"); - } - } - - /** - * Search for a list of nodes using the specific search context - * - * @param searchContext To use to perform the search - */ - private void searchBrowseNodes(SearchContext searchContext) - { - long startTime = 0; - if (logger.isDebugEnabled()) - startTime = System.currentTimeMillis(); - - // get the searcher object to build the query - String query = searchContext.buildQuery(getMinimumSearchLength()); - if (query == null) - { - // failed to build a valid query, the user probably did not enter the - // minimum text required to construct a valid search - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), MSG_SEARCH_MINIMUM), - new Object[] {getMinimumSearchLength()})); - this.containerNodes = Collections.emptyList(); - this.contentNodes = Collections.emptyList(); - return; - } - - // perform the search against the repo - UserTransaction tx = null; - ResultSet results = null; - try - { - tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true); - tx.begin(); - - // build up the search parameters - SearchParameters sp = new SearchParameters(); - sp.setLanguage(SearchService.LANGUAGE_LUCENE); - sp.setQuery(query); - sp.addStore(Repository.getStoreRef()); - - // limit search results size as configured - int searchLimit = Application.getClientConfig(FacesContext.getCurrentInstance()).getSearchMaxResults(); - if (searchLimit > 0) - { - sp.setLimitBy(LimitBy.FINAL_SIZE); - sp.setLimit(searchLimit); - } - - sp.setBulkFetchEnabled(Application.getClientConfig(FacesContext.getCurrentInstance()).isBulkFetchEnabled()); - - results = this.getSearchService().query(sp); - if (logger.isDebugEnabled()) - logger.debug("Search results returned: " + results.length()); - - // create a list of items from the results - this.containerNodes = new ArrayList(results.length()); - this.contentNodes = new ArrayList(results.length()); - if (results.length() != 0) - { - // in case of dynamic config, only lookup once - Set nodeEventListeners = getNodeEventListeners(); - - for (ResultSetRow row: results) - { - NodeRef nodeRef = row.getNodeRef(); - - if (this.getNodeService().exists(nodeRef)) - { - // find it's type so we can see if it's a node we are interested in - QName type = this.getNodeService().getType(nodeRef); - - // make sure the type is defined in the data dictionary - TypeDefinition typeDef = this.getDictionaryService().getType(type); - - if (typeDef != null) - { - MapNode node = null; - - // look for Space or File nodes - if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_FOLDER) && - this.getDictionaryService().isSubClass(type, ContentModel.TYPE_SYSTEM_FOLDER) == false) - { - // create our Node representation - node = new MapNode(nodeRef, this.getNodeService(), false); - - node.addPropertyResolver("path", this.resolverPath); - node.addPropertyResolver("displayPath", this.resolverDisplayPath); - node.addPropertyResolver("icon", this.resolverSpaceIcon); - node.addPropertyResolver("smallIcon", this.resolverSmallIcon); - - this.containerNodes.add(node); - } - else if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_CONTENT)) - { - // create our Node representation - node = new MapNode(nodeRef, this.getNodeService(), false); - - setupCommonBindingProperties(node); - - node.addPropertyResolver("path", this.resolverPath); - node.addPropertyResolver("displayPath", this.resolverDisplayPath); - - this.contentNodes.add(node); - } - // look for File Link object node - else if (ApplicationModel.TYPE_FILELINK.equals(type)) - { - // create our File Link Node representation - node = new MapNode(nodeRef, this.getNodeService(), false); - // only display the user has the permissions to navigate to the target of the link - NodeRef destRef = (NodeRef)node.getProperties().get(ContentModel.PROP_LINK_DESTINATION); - if (new Node(destRef).hasPermission(PermissionService.READ) == true) - { - node.addPropertyResolver("url", this.resolverLinkUrl); - node.addPropertyResolver("downloadUrl", this.resolverLinkDownload); - node.addPropertyResolver("webdavUrl", this.resolverLinkWebdavUrl); - node.addPropertyResolver("cifsPath", this.resolverLinkCifsPath); - node.addPropertyResolver("fileType16", this.resolverFileType16); - node.addPropertyResolver("fileType32", this.resolverFileType32); - node.addPropertyResolver("lang", this.resolverLang); - node.addPropertyResolver("path", this.resolverPath); - node.addPropertyResolver("displayPath", this.resolverDisplayPath); - - this.contentNodes.add(node); - } - } - else if (ApplicationModel.TYPE_FOLDERLINK.equals(type)) - { - // create our Folder Link Node representation - node = new MapNode(nodeRef, this.getNodeService(), false); - // only display the user has the permissions to navigate to the target of the link - NodeRef destRef = (NodeRef)node.getProperties().get(ContentModel.PROP_LINK_DESTINATION); - if (new Node(destRef).hasPermission(PermissionService.READ) == true) - { - node.addPropertyResolver("icon", this.resolverSpaceIcon); - node.addPropertyResolver("smallIcon", this.resolverSmallIcon); - node.addPropertyResolver("path", this.resolverPath); - node.addPropertyResolver("displayPath", this.resolverDisplayPath); - - this.containerNodes.add(node); - } - } - - // inform any listeners that a Node wrapper has been created - if (node != null) - { - for (NodeEventListener listener : nodeEventListeners) - { - listener.created(node, type); - } - } - } - else - { - if (logger.isWarnEnabled()) - logger.warn("Found invalid object in database: id = " + nodeRef + ", type = " + type); - } - } - else - { - if (logger.isWarnEnabled()) - logger.warn("Missing object returned from search indexes: id = " + nodeRef + " search query: " + query); - } - } - } - - // commit the transaction - tx.commit(); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {refErr.getNodeRef()}), refErr ); - this.containerNodes = Collections.emptyList(); - this.contentNodes = Collections.emptyList(); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - catch (SearcherException serr) - { - logger.info("Search failed for: " + query, serr); - Utils.addErrorMessage(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_QUERY)); - this.containerNodes = Collections.emptyList(); - this.contentNodes = Collections.emptyList(); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_SEARCH), new Object[] {err.getMessage()}), err ); - this.containerNodes = Collections.emptyList(); - this.contentNodes = Collections.emptyList(); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - finally - { - if (results != null) - { - results.close(); - } - } - - if (logger.isDebugEnabled()) - { - long endTime = System.currentTimeMillis(); - logger.debug("Time to query and build map nodes: " + (endTime - startTime) + "ms"); - } - } - - - // ------------------------------------------------------------------------------ - // Property Resolvers - - public NodePropertyResolver resolverDownload = new NodePropertyResolver() { - private static final long serialVersionUID = 4048859853585650378L; - - public Object get(Node node) { - return DownloadContentServlet.generateDownloadURL(node.getNodeRef(), node.getName()); - } - }; - - public NodePropertyResolver resolverUrl = new NodePropertyResolver() { - private static final long serialVersionUID = -5264085143622470386L; - - public Object get(Node node) { - return DownloadContentServlet.generateBrowserURL(node.getNodeRef(), node.getName()); - } - }; - - public NodePropertyResolver resolverWebdavUrl = new NodePropertyResolver() { - private static final long serialVersionUID = 9127234483419089006L; - - public Object get(Node node) { - return Utils.generateURL(FacesContext.getCurrentInstance(), node, URLMode.WEBDAV); - } - }; - - public NodePropertyResolver resolverCifsPath = new NodePropertyResolver() { - private static final long serialVersionUID = -5804924617772163104L; - - public Object get(Node node) { - return Utils.generateURL(FacesContext.getCurrentInstance(), node, URLMode.CIFS); - } - }; - - public NodePropertyResolver resolverLinkDownload = new NodePropertyResolver() { - private static final long serialVersionUID = 7208696954599958859L; - - public Object get(Node node) { - NodeRef destRef = (NodeRef)node.getProperties().get(ContentModel.PROP_LINK_DESTINATION); - if (getNodeService().exists(destRef) == true) - { - String destName = Repository.getNameForNode(getNodeService(), destRef); - return DownloadContentServlet.generateDownloadURL(destRef, destName); - } - else - { - // TODO: link object is missing - navigate to a page with appropriate message - return "#"; - } - } - }; - - public NodePropertyResolver resolverLinkUrl = new NodePropertyResolver() { - private static final long serialVersionUID = -1280702397805414147L; - - public Object get(Node node) { - NodeRef destRef = (NodeRef)node.getProperties().get(ContentModel.PROP_LINK_DESTINATION); - if (getNodeService().exists(destRef) == true) - { - String destName = Repository.getNameForNode(getNodeService(), destRef); - return DownloadContentServlet.generateBrowserURL(destRef, destName); - } - else - { - // TODO: link object is missing - navigate to a page with appropriate message - return "#"; - } - } - }; - - public NodePropertyResolver resolverLinkWebdavUrl = new NodePropertyResolver() { - private static final long serialVersionUID = -3097558079118837397L; - - public Object get(Node node) { - NodeRef destRef = (NodeRef)node.getProperties().get(ContentModel.PROP_LINK_DESTINATION); - if (getNodeService().exists(destRef) == true) - { - return Utils.generateURL(FacesContext.getCurrentInstance(), new Node(destRef), URLMode.WEBDAV); - } - else - { - // TODO: link object is missing - navigate to a page with appropriate message - return "#"; - } - } - }; - - public NodePropertyResolver resolverLinkCifsPath = new NodePropertyResolver() { - private static final long serialVersionUID = 673020173327603487L; - - public Object get(Node node) { - NodeRef destRef = (NodeRef)node.getProperties().get(ContentModel.PROP_LINK_DESTINATION); - if (getNodeService().exists(destRef) == true) - { - return Utils.generateURL(FacesContext.getCurrentInstance(), new Node(destRef), URLMode.CIFS); - } - else - { - // TODO: link object is missing - navigate to a page with appropriate message - return "#"; - } - } - }; - - public NodePropertyResolver resolverFileType16 = new NodePropertyResolver() { - private static final long serialVersionUID = -2690520488415178029L; - - public Object get(Node node) { - return FileTypeImageUtils.getFileTypeImage(node.getName(), true); - } - }; - - public NodePropertyResolver resolverFileType32 = new NodePropertyResolver() { - private static final long serialVersionUID = 1991254398502584389L; - - public Object get(Node node) { - return FileTypeImageUtils.getFileTypeImage(node.getName(), false); - } - }; - - public NodePropertyResolver resolverPath = new NodePropertyResolver() { - private static final long serialVersionUID = 8008094870888545035L; - - public Object get(Node node) { - return node.getNodePath(); - } - }; - - public NodePropertyResolver resolverDisplayPath = new NodePropertyResolver() { - private static final long serialVersionUID = -918422848579179425L; - - public Object get(Node node) { - // TODO: replace this with a method that shows the full display name - not QNames? - return Repository.getDisplayPath(node.getNodePath()); - } - }; - - public NodePropertyResolver resolverSpaceIcon = new NodePropertyResolver() { - private static final long serialVersionUID = -5644418026591098018L; - - public Object get(Node node) { - QNameNodeMap props = (QNameNodeMap)node.getProperties(); - String icon = (String)props.getRaw("app:icon"); - return (icon != null ? icon : CreateSpaceWizard.DEFAULT_SPACE_ICON_NAME); - } - }; - - public NodePropertyResolver resolverSmallIcon = new NodePropertyResolver() { - private static final long serialVersionUID = -150483121767183580L; - - public Object get(Node node) { - QNameNodeMap props = (QNameNodeMap)node.getProperties(); - String icon = (String)props.getRaw("app:icon"); - return (icon != null ? icon + "-16" : SPACE_SMALL_DEFAULT); - } - }; - - public NodePropertyResolver resolverMimetype = new NodePropertyResolver() { - private static final long serialVersionUID = -8864267975247235172L; - - public Object get(Node node) { - ContentData content = (ContentData)node.getProperties().get(ContentModel.PROP_CONTENT); - return (content != null ? content.getMimetype() : null); - } - }; - - public NodePropertyResolver resolverEncoding = new NodePropertyResolver() { - private static final long serialVersionUID = -1130974681844152101L; - - public Object get(Node node) { - ContentData content = (ContentData)node.getProperties().get(ContentModel.PROP_CONTENT); - return (content != null ? content.getEncoding() : null); - } - }; - - public NodePropertyResolver resolverSize = new NodePropertyResolver() { - private static final long serialVersionUID = 1273541660444385276L; - - public Object get(Node node) { - ContentData content = (ContentData)node.getProperties().get(ContentModel.PROP_CONTENT); - return (content != null ? new Long(content.getSize()) : 0L); - } - }; - - public NodePropertyResolver resolverLang = new NodePropertyResolver() { - - private static final long serialVersionUID = 5412446489528560367L; - - public Object get(Node node) { - - String lang = null; - - if (node.getAspects().contains(ContentModel.ASPECT_MULTILINGUAL_DOCUMENT)) - { - Locale locale = null; - - if(node.hasAspect(ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION)) - { - // if the translation is empty, the lang of the content is the lang of it's pivot. - NodeRef pivot = getMultilingualContentService().getPivotTranslation(node.getNodeRef()); - locale = (Locale) getNodeService().getProperty(pivot, ContentModel.PROP_LOCALE); - } - else - { - locale = (Locale) node.getProperties().get(ContentModel.PROP_LOCALE); - } - // the content filter lang defined by the user - String userLang = userPreferencesBean.getContentFilterLanguage(); - // the node lang - String nodeLang = locale.getLanguage(); - - // if filter equals all languages : display the lang for each translation - if (nodeLang == null) - { - lang = nodeLang; - } - - // if filter is different : display the lang - else if (!nodeLang.equalsIgnoreCase(userLang)) - { - lang = nodeLang; - } - - // else if the filter is equal to the lang node : nothing to do [lang = null] - } - - return lang; - } - }; - - - // ------------------------------------------------------------------------------ - // Navigation action event handlers - - /** - * Action called from the Simple Search component. - * Sets up the SearchContext object with the values from the simple search menu. - */ - public void search(ActionEvent event) - { - // setup the search text string on the top-level navigation handler - UISimpleSearch search = (UISimpleSearch)event.getComponent(); - this.navigator.setSearchContext(search.getSearchContext()); - - navigateBrowseScreen(); - } - - /** - * Action called to Close the search dialog by returning to the last view node Id - */ - public void closeSearch(ActionEvent event) - { - // set the current node Id ready for page refresh - String currentNodeId = this.navigator.getCurrentNodeId(); - this.navigator.setCurrentNodeId(currentNodeId); - - // setup dispatch context so we go back to the right place - NodeRef currentNodeRef = new NodeRef(Repository.getStoreRef(), currentNodeId); - Node currentNode = new Node(currentNodeRef); - this.navigator.setupDispatchContext(currentNode); - } - - /** - * Update page size based on user selection - */ - public void updateSpacesPageSize(ActionEvent event) - { - try - { - int size = Integer.parseInt(this.pageSizeSpacesStr); - if (size >= 0) - { - this.pageSizeSpaces = size; - } - else - { - // reset to known value if this occurs - this.pageSizeSpacesStr = Integer.toString(this.pageSizeSpaces); - } - } - catch (NumberFormatException err) - { - // reset to known value if this occurs - this.pageSizeSpacesStr = Integer.toString(this.pageSizeSpaces); - } - } - - /** - * Update page size based on user selection - */ - public void updateContentPageSize(ActionEvent event) - { - try - { - int size = Integer.parseInt(this.pageSizeContentStr); - if (size >= 0) - { - this.pageSizeContent = size; - } - else - { - // reset to known value if this occurs - this.pageSizeContentStr = Integer.toString(this.pageSizeContent); - } - } - catch (NumberFormatException err) - { - // reset to known value if this occurs - this.pageSizeContentStr = Integer.toString(this.pageSizeContent); - } - } - - /** - * Action called when a folder space is clicked. - * Navigate into the space. - */ - public void clickSpace(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - try - { - NodeRef ref = new NodeRef(Repository.getStoreRef(), id); - - // handle special folder link node case - if (ApplicationModel.TYPE_FOLDERLINK.equals(this.getNodeService().getType(ref))) - { - ref = (NodeRef)this.getNodeService().getProperty(ref, ContentModel.PROP_LINK_DESTINATION); - } - - clickSpace(ref); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {id}) ); - } - } - } - - /** - * Action called when a folder space is clicked. - * - * @param nodeRef The node being clicked - */ - public void clickSpace(NodeRef nodeRef) - { - // refresh UI based on node selection - updateUILocation(nodeRef); - } - - /** - * Handler called when a path element is clicked - navigate to the appropriate Space - */ - public void clickSpacePath(ActionEvent event) - { - UINodePath.PathElementEvent pathEvent = (UINodePath.PathElementEvent)event; - NodeRef ref = pathEvent.NodeReference; - try - { - // refresh UI based on node selection - this.updateUILocation(ref); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {ref.getId()}) ); - } - } - - /** - * Action called when a folders direct descendant (in the 'list' browse mode) is clicked. - * Navigate into the the descendant space. - */ - public void clickDescendantSpace(ActionEvent event) - { - UINodeDescendants.NodeSelectedEvent nodeEvent = (UINodeDescendants.NodeSelectedEvent)event; - NodeRef nodeRef = nodeEvent.NodeReference; - if (nodeRef == null) - { - throw new IllegalStateException("NodeRef returned from UINodeDescendants.NodeSelectedEvent cannot be null!"); - } - - if (logger.isDebugEnabled()) - logger.debug("Selected noderef Id: " + nodeRef.getId()); - - try - { - // user can either select a descendant of a node display on the page which means we - // must add the it's parent and itself to the breadcrumb - ChildAssociationRef parentAssocRef = getNodeService().getPrimaryParent(nodeRef); - - if (logger.isDebugEnabled()) - { - logger.debug("Selected item getPrimaryParent().getChildRef() noderef Id: " + parentAssocRef.getChildRef().getId()); - logger.debug("Selected item getPrimaryParent().getParentRef() noderef Id: " + parentAssocRef.getParentRef().getId()); - logger.debug("Current value getNavigator().getCurrentNodeId() noderef Id: " + this.navigator.getCurrentNodeId()); - } - - if (nodeEvent.IsParent == false) - { - // a descendant of the displayed node was selected - // first refresh based on the parent and add to the breadcrumb - updateUILocation(parentAssocRef.getParentRef()); - - // now add our selected node - updateUILocation(nodeRef); - } - else - { - // else the parent ellipses i.e. the displayed node was selected - updateUILocation(nodeRef); - } - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {nodeRef.getId()}) ); - } - } - - /** - * Action event called by all Browse actions that need to setup a Space context - * before an action page/wizard is called. The context will be a Node in setActionSpace() which - * can be retrieved on the action page from BrowseBean.getActionSpace(). - * - * @param event ActionEvent - */ - public void setupSpaceAction(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - setupSpaceAction(id, true); - } - - /** - * Public helper to setup action pages with Space context - * - * @param id of the Space node to setup context for - */ - public void setupSpaceAction(String id, boolean invalidate) - { - if (id != null && id.length() != 0) - { - if (logger.isDebugEnabled()) - logger.debug("Setup for action, setting current space to: " + id); - - try - { - // create the node ref, then our node representation - NodeRef ref = new NodeRef(Repository.getStoreRef(), id); - Node node = new Node(ref); - - // resolve icon in-case one has not been set - node.addPropertyResolver("icon", this.resolverSpaceIcon); - - // prepare a node for the action context - setActionSpace(node); - - // setup the dispatch context in case it is required - this.navigator.setupDispatchContext(node); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {id}) ); - } - } - else - { - setActionSpace(null); - } - - // clear the UI state in preparation for finishing the next action - if (invalidate == true) - { - // use the context service to notify all registered beans - UIContextService.getInstance(FacesContext.getCurrentInstance()).notifyBeans(); - } - } - - /** - * Acrtion event called by Delete Space actions. We setup the action space as normal, then prepare - * any special case message string to be shown to the user if they are trying to delete specific spaces. - */ - public void setupDeleteAction(ActionEvent event) - { - String message = null; - - setupSpaceAction(event); - - Node node = getActionSpace(); - if (node != null) - { - FacesContext fc = FacesContext.getCurrentInstance(); - NodeRef companyRootRef = new NodeRef(Repository.getStoreRef(), Application.getCompanyRootId(fc)); - if (node.getNodeRef().equals(companyRootRef)) - { - message = Application.getMessage(fc, MSG_DELETE_COMPANYROOT); - } - } - - setDeleteMessage(message); - } - - /** - * Action event called by all actions that need to setup a Content Document context on the - * BrowseBean before an action page/wizard is called. The context will be a Node in - * setDocument() which can be retrieved on the action page from BrowseBean.getDocument(). - */ - public void setupContentAction(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - setupContentAction(params.get("id"), true); - } - - /** - * Action event called by all actions that need to setup a Multilingual Content Document context on the - * BrowseBean before an action page/wizard is called. The context will be a Node in - * setDocument() which can be retrieved on the action page from BrowseBean.getDocument(). - */ - public void setupMLContainerContentAction(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - - String id = params.get("id"); - - NodeRef translation = new NodeRef(Repository.getStoreRef(), id); - - // remember the bean from which the action comes - FacesContext fc = FacesContext.getCurrentInstance(); - DocumentDetailsDialog docDetails = (DocumentDetailsDialog)FacesHelper.getManagedBean(fc, "DocumentDetailsDialog"); - docDetails.setTranslationDocument(new MapNode(translation)); - MultilingualManageDialog mmDialog = (MultilingualManageDialog)FacesHelper.getManagedBean(fc, "MultilingualManageDialog"); - mmDialog.setTranslationDocument(docDetails.getTranslationDocument()); - - // set the ml container as the current document - NodeRef mlContainer = getMultilingualContentService().getTranslationContainer(translation); - - setupContentAction(mlContainer.getId(), true); - } - - /** - * Public helper to setup action pages with content context - * - * @param id of the content node to setup context for - */ - public void setupContentAction(String id, boolean invalidate) - { - if (id != null && id.length() != 0) - { - if (logger.isDebugEnabled()) - logger.debug("Setup for action, setting current document to: " + id); - - try - { - // create the node ref, then our node representation - NodeRef ref = new NodeRef(Repository.getStoreRef(), id); - Node node = new MapNode(ref); - - // store the URL to for downloading the content - if (ApplicationModel.TYPE_FILELINK.equals(node.getType())) - { - node.addPropertyResolver("url", this.resolverLinkDownload); - node.addPropertyResolver("downloadUrl", this.resolverLinkDownload); - } - else - { - node.addPropertyResolver("url", this.resolverDownload); - node.addPropertyResolver("downloadUrl", this.resolverDownload); - } - node.addPropertyResolver("webdavUrl", this.resolverWebdavUrl); - node.addPropertyResolver("cifsPath", this.resolverCifsPath); - node.addPropertyResolver("fileType32", this.resolverFileType32); - node.addPropertyResolver("mimetype", this.resolverMimetype); - node.addPropertyResolver("encoding", this.resolverEncoding); - node.addPropertyResolver("size", this.resolverSize); - node.addPropertyResolver("lang", this.resolverLang); - - for (NodeEventListener listener : getNodeEventListeners()) - { - listener.created(node, node.getType()); - } - - // get hold of the DocumentDetailsDialog and reset it - DocumentDetailsDialog docDetails = (DocumentDetailsDialog)FacesContext.getCurrentInstance(). - getExternalContext().getSessionMap().get("DocumentDetailsDialog"); - if (docDetails != null) - { - docDetails.reset(); - } - - // remember the document - setDocument(node); - - // setup the dispatch context in case it is required - this.navigator.setupDispatchContext(node); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {id}) ); - throw new AbortProcessingException("Invalid node reference"); - } - } - else - { - setDocument(null); - } - - // clear the UI state in preparation for finishing the next action - if (invalidate == true) - { - // use the context service to notify all registered beans - UIContextService.getInstance(FacesContext.getCurrentInstance()).notifyBeans(); - } - } - - /** - * Removes the given node from the breadcrumb i.e. following a delete - * - * @param node The space to remove from the breadcrumb - */ - public void removeSpaceFromBreadcrumb(Node node) - { - List location = navigator.getLocation(); - IBreadcrumbHandler handler = location.get(location.size() - 1); - if (handler instanceof IRepoBreadcrumbHandler) - { - // see if the current breadcrumb location is our node - if ( ((IRepoBreadcrumbHandler)handler).getNodeRef().equals(node.getNodeRef()) == true ) - { - location.remove(location.size() - 1); - - // now work out which node to set the list to refresh against - if (location.size() != 0) - { - handler = location.get(location.size() - 1); - - if (handler instanceof IRepoBreadcrumbHandler) - { - // change the current node Id - navigator.setCurrentNodeId(((IRepoBreadcrumbHandler)handler).getNodeRef().getId()); - } - else - { - // if we don't have access to the NodeRef to go to next then go to the home space - navigator.processToolbarLocation(NavigationBean.LOCATION_HOME, false); - } - } - else - { - // if there is no breadcrumb left go to the user's home space - navigator.processToolbarLocation(NavigationBean.LOCATION_HOME, false); - } - } - } - } - - /** - * Support for refresh of lists via special case for an External Access URL. - * these URLs restart the JSF lifecycle but an old UIRichList is restored from - * the component tree - which needs clearing "late" in the lifecycle process. - */ - public void externalAccessRefresh() - { - this.externalForceRefresh = true; - } - - /** - * Save the state of the panel that was expanded/collapsed - */ - public void expandPanel(ActionEvent event) - { - if (event instanceof ExpandedEvent) - { - String id = event.getComponent().getId(); - this.panels.put(id, ((ExpandedEvent)event).State); - } - } - - - // ------------------------------------------------------------------------------ - // Private helpers - - /** - * Initialise default values from client configuration - */ - private void initFromClientConfig() - { - // TODO - review implications of these default values on dynamic/MT client: viewsConfig & browseViewMode, as well as page size content/spaces ... - ConfigService config = Application.getConfigService(FacesContext.getCurrentInstance()); - - this.viewsConfig = (ViewsConfigElement)config.getConfig("Views"). - getConfigElement(ViewsConfigElement.CONFIG_ELEMENT_ID); - - this.browseViewMode = this.viewsConfig.getDefaultView(PAGE_NAME_BROWSE); - int pageSize = this.viewsConfig.getDefaultPageSize(PAGE_NAME_BROWSE, this.browseViewMode); - setPageSizeContent(pageSize); - setPageSizeSpaces(pageSize); - } - - /** - * @return the Set of NodeEventListeners registered against this bean - */ - private Set getNodeEventListeners() - { - if ((this.nodeEventListeners == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - Set allNodeEventListeners = new HashSet(); - - if (Application.isDynamicConfig(FacesContext.getCurrentInstance()) && (this.nodeEventListeners != null)) - { - // for dynamic config, can add/remove node event listeners dynamically ... - // however, in case anyone is using public methods (add/removeNodeEventListener) - // we merge list here with list returned from the config - allNodeEventListeners.addAll(this.nodeEventListeners); - } - - FacesContext fc = FacesContext.getCurrentInstance(); - Config listenerConfig = Application.getConfigService(fc).getConfig("Node Event Listeners"); - if (listenerConfig != null) - { - ConfigElement listenerElement = listenerConfig.getConfigElement("node-event-listeners"); - if (listenerElement != null) - { - for (ConfigElement child : listenerElement.getChildren()) - { - if (child.getName().equals("listener")) - { - // retrieved the JSF Managed Bean identified in the config - String listenerName = child.getValue().trim(); - Object bean = FacesHelper.getManagedBean(fc, listenerName); - if (bean instanceof NodeEventListener) - { - allNodeEventListeners.add((NodeEventListener)bean); - } - } - } - } - } - - if (Application.isDynamicConfig(FacesContext.getCurrentInstance())) - { - return allNodeEventListeners; - } - else - { - this.nodeEventListeners = allNodeEventListeners; - } - } - return this.nodeEventListeners; - } - - /** - * Refresh the UI after a Space selection change. Adds the selected space to the breadcrumb - * location path and also updates the list components in the UI. - * - * @param ref NodeRef of the selected space - */ - public void updateUILocation(NodeRef ref) - { - // get the current breadcrumb location and append a new handler to it - // our handler know the ID of the selected node and the display label for it - List location = this.navigator.getLocation(); - if (location.size() != 0) - { - // attempt to find the ID - if it's already in the breadcrumb then we - // navigate directly to that node - rather than add duplication to the breadcrumb path - boolean foundNode = false; - for (int i=0; i newLocation = new ArrayList(i+1); - //newLocation.addAll(location.subList(0, i + 1)); - //this.navigator.setLocation(newLocation); - // TODO: but instead for now we do this: - int count = location.size(); - for (int n=i+1; n params = link.getParameterMap(); - - String ref = params.get("ref"); - if (ref != null && ref.length() > 0) - { - NodeRef nodeRef = new NodeRef(ref); - - NodeRef workingCopyNodeRef = getCheckOutCheckInService().getWorkingCopy(nodeRef); - - if (workingCopyNodeRef != null) - { - // if node has a working copy setup error message and return - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), MSG_CANNOT_DELETE_NODE_HAS_WORKING_COPY), - new Object[] {getNodeService().getProperty(nodeRef, ContentModel.PROP_NAME)})); - return; - } - - // if there isn't a working copy go to normal delete dialog - boolean hasMultipleParents = false; - boolean showDeleteAssocDialog = false; - - // get type of node being deleted - Node node = this.getDocument(); - QName type = node.getType(); - TypeDefinition typeDef = this.dictionaryService.getType(type); - - // determine if the node being delete has multiple parents - if (!type.equals(ContentModel.TYPE_MULTILINGUAL_CONTAINER) && - !node.hasAspect(ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION) && - !node.hasAspect(ContentModel.ASPECT_MULTILINGUAL_DOCUMENT) && - !type.equals(ContentModel.TYPE_LINK) && - !this.dictionaryService.isSubClass(typeDef.getName(), ContentModel.TYPE_LINK)) - { - List parents = this.nodeService.getParentAssocs(node.getNodeRef(), - ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL); - if (parents != null && parents.size() > 1) - { - hasMultipleParents = true; - } - } - - // determine which delete dialog to display - if (this.navigator.getSearchContext() == null && hasMultipleParents) - { - // if we are not in a search and the node has multiple parents - // see if the current node has the primary parent association - NodeRef parentSpace = this.navigator.getCurrentNode().getNodeRef(); - ChildAssociationRef assoc = this.nodeService.getPrimaryParent(node.getNodeRef()); - - // show delete assoc dialog if the current space is not the primary parent for the node - showDeleteAssocDialog = !parentSpace.equals(assoc.getParentRef()); - } - - // show the appropriate dialog - FacesContext fc = FacesContext.getCurrentInstance(); - if (showDeleteAssocDialog) - { - fc.getApplication().getNavigationHandler().handleNavigation(fc, null, "dialog:deleteFileAssoc"); - } - else - { - final Map dialogParams = new HashMap(1); - dialogParams.put("hasMultipleParents", Boolean.toString(hasMultipleParents)); - Application.getDialogManager().setupParameters(dialogParams); - fc.getApplication().getNavigationHandler().handleNavigation(fc, null, "dialog:deleteFile"); - } - } - } - - /** - * Handles the deleteSpace action by deciding which delete dialog to display - */ - public void deleteSpace(ActionEvent event) - { - setupDeleteAction(event); - - boolean hasMultipleParents = false; - boolean showDeleteAssocDialog = false; - - // determine if the node being delete has multiple parents - Node node = this.getActionSpace(); - List parents = this.nodeService.getParentAssocs(node.getNodeRef(), - ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL); - if (parents != null && parents.size() > 1) - { - hasMultipleParents = true; - } - - // determine which delete dialog to display - if (this.navigator.getSearchContext() == null && hasMultipleParents) - { - // if we are not in a search and the node has multiple parents - // see if the current node has the primary parent association - NodeRef parentSpace = this.navigator.getCurrentNode().getNodeRef(); - ChildAssociationRef assoc = this.nodeService.getPrimaryParent(node.getNodeRef()); - - // show delete assoc dialog if the current space is not the primary parent for the node - showDeleteAssocDialog = !parentSpace.equals(assoc.getParentRef()); - } - - // show the appropriate dialog - FacesContext fc = FacesContext.getCurrentInstance(); - if (showDeleteAssocDialog) - { - fc.getApplication().getNavigationHandler().handleNavigation(fc, null, "dialog:deleteSpaceAssoc"); - } - else - { - final Map dialogParams = new HashMap(1); - dialogParams.put("hasMultipleParents", Boolean.toString(hasMultipleParents)); - Application.getDialogManager().setupParameters(dialogParams); - fc.getApplication().getNavigationHandler().handleNavigation(fc, null, "dialog:deleteSpace"); - } - } - - // ------------------------------------------------------------------------------ - // Inner classes - - /** - * Class to handle breadcrumb interaction for Browse pages - */ - private class BrowseBreadcrumbHandler implements IRepoBreadcrumbHandler - { - private static final long serialVersionUID = 3833183653173016630L; - - /** - * Constructor - * - * @param nodeRef The NodeRef for this browse navigation element - * @param label Element label - */ - public BrowseBreadcrumbHandler(NodeRef nodeRef, String label) - { - this.label = label; - this.nodeRef = nodeRef; - } - - /** - * @see java.lang.Object#toString() - */ - public String toString() - { - return this.label; - } - - /** - * @see org.alfresco.web.ui.common.component.IBreadcrumbHandler#navigationOutcome(org.alfresco.web.ui.common.component.UIBreadcrumb) - */ - @SuppressWarnings("unchecked") - public String navigationOutcome(UIBreadcrumb breadcrumb) - { - // All browse breadcrumb element relate to a Node Id - when selected we - // set the current node id - navigator.setCurrentNodeId(this.nodeRef.getId()); - navigator.setLocation( (List)breadcrumb.getValue() ); - - // setup the dispatch context - navigator.setupDispatchContext(new Node(this.nodeRef)); - - // inform any listeners that the current space has changed - UIContextService.getInstance(FacesContext.getCurrentInstance()).spaceChanged(); - - // return to browse page if required - return (isViewCurrent() ? null : "browse"); - } - - public NodeRef getNodeRef() - { - return this.nodeRef; - } - - private NodeRef nodeRef; - private String label; - } - - - // ------------------------------------------------------------------------------ - // Private data - - private static Log logger = LogFactory.getLog(BrowseBean.class); - - /** Browse screen view ID */ - public static final String BROWSE_VIEW_ID = "/jsp/browse/browse.jsp"; - public static final String CATEGORY_VIEW_ID = "/jsp/browse/category-browse.jsp"; - - /** Small icon default name */ - public static final String SPACE_SMALL_DEFAULT = "space_small"; - - private static final String VIEWMODE_DASHBOARD = "dashboard"; - private static final String PAGE_NAME_BROWSE = "browse"; - - /** I18N messages */ - private static final String MSG_DELETE_COMPANYROOT = "delete_companyroot_confirm"; - public static final String MSG_SEARCH_MINIMUM = "search_minimum"; - private static final String MSG_CANNOT_DELETE_NODE_HAS_WORKING_COPY = "cannot_delete_node_has_working_copy"; - - /** The NodeService to be used by the bean */ - private transient NodeService nodeService; - - /** The CheckOutCheckInService to be used by the bean */ - private transient CheckOutCheckInService checkOutCheckInService; - - /** The SearchService to be used by the bean */ - private transient SearchService searchService; - - /** The LockService to be used by the bean */ - private transient LockService lockService; - - /** The NavigationBean bean reference */ - protected NavigationBean navigator; - - /** The UserPreferencesBean to be used by the bean */ - protected UserPreferencesBean userPreferencesBean; - - /** The DictionaryService bean reference */ - private transient DictionaryService dictionaryService; - - /** The file folder service */ - private transient FileFolderService fileFolderService; - - /** The Multilingual Content Service */ - private transient MultilingualContentService multilingualContentService; - - /** Views configuration object */ - protected ViewsConfigElement viewsConfig = null; - - /** Listeners for Node events */ - protected Set nodeEventListeners = null; - - /** Collapsable Panel state */ - private Map panels = new HashMap(4, 1.0f); - - /** Component references */ - protected UIRichList spacesRichList; - protected UIRichList contentRichList; - private UIStatusMessage statusMessage; - - /** Transient lists of container and content nodes for display */ - protected List containerNodes = null; - protected List contentNodes = null; - protected List parentContainerNodes = null; - - /** The current space and it's properties - if any */ - protected Node actionSpace; - - /** The current document */ - protected Node document; - - /** Special message to display when user deleting certain folders e.g. Company Home */ - private String deleteMessage; - - /** The current browse view mode - set to a well known IRichListRenderer identifier */ - private String browseViewMode; - - /** The current browse view page sizes */ - private int pageSizeSpaces; - private int pageSizeContent; - private String pageSizeSpacesStr; - private String pageSizeContentStr; - - /** True if current space has a dashboard (template) view available */ - private boolean dashboardView; - - private boolean externalForceRefresh = false; -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/bean/CategoriesProperties.java b/war/src/main/java/org/alfresco/web/bean/CategoriesProperties.java deleted file mode 100644 index d68b631090..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/CategoriesProperties.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean; - -import java.util.Collection; -import java.util.List; - -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; - -import org.alfresco.service.cmr.search.CategoryService; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.ui.common.component.IBreadcrumbHandler; -import org.alfresco.web.ui.common.component.data.UIRichList; - -public class CategoriesProperties -{ - - protected CategoryService categoryService; - - /** Component references */ - protected UIRichList categoriesRichList; - - /** Currently visible category Node */ - private Node category = null; - - /** Current category ref */ - private NodeRef categoryRef = null; - - /** Action category node */ - private Node actionCategory = null; - - /** Members of the linked items of a category */ - private Collection members = null; - - /** Dialog properties */ - private String name = null; - private String description = null; - - /** RichList view mode */ - private String viewMode = "icons"; - - /** Category path breadcrumb location */ - private List location = null; - - public CategoryService getCategoryService() - { - return categoryService; - } - - public void setCategoryService(CategoryService categoryService) - { - this.categoryService = categoryService; - } - - public UIRichList getCategoriesRichList() - { - return categoriesRichList; - } - - public void setCategoriesRichList(UIRichList categoriesRichList) - { - this.categoriesRichList = categoriesRichList; - } - - public Node getCategory() - { - return category; - } - - public void setCategory(Node category) - { - this.category = category; - } - - public NodeRef getCategoryRef() - { - return categoryRef; - } - - public void setCategoryRef(NodeRef categoryRef) - { - this.categoryRef = categoryRef; - } - - public Node getActionCategory() - { - return actionCategory; - } - - public void setActionCategory(Node actionCategory) - { - this.actionCategory = actionCategory; - } - - public Collection getMembers() - { - return members; - } - - public void setMembers(Collection members) - { - this.members = members; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name; - } - - public String getDescription() - { - return description; - } - - public void setDescription(String description) - { - this.description = description; - } - - public String getViewMode() - { - return viewMode; - } - - public void setViewMode(String viewMode) - { - this.viewMode = viewMode; - } - - public List getLocation() - { - return location; - } - - public void setLocation(List location) - { - this.location = location; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/CategoryBrowserBean.java b/war/src/main/java/org/alfresco/web/bean/CategoryBrowserBean.java deleted file mode 100644 index 4310e4adf9..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/CategoryBrowserBean.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.web.bean.search.SearchContext; - -public class CategoryBrowserBean -{ - public static String BEAN_NAME = "CategoryBrowserBean"; - - private NodeService nodeService; - - private NodeRef currentCategory = null; - - private boolean includeSubcategories = false; - - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - public void setCurrentCategory(NodeRef currentCategory) - { - this.currentCategory = currentCategory; - } - - public String getCurrentCategoryName() - { - String currentCategoryName = null; - if (currentCategory != null) - currentCategoryName = (String) this.nodeService.getProperty(currentCategory, ContentModel.PROP_NAME); - - return currentCategoryName; - } - - public boolean isIncludeSubcategories() - { - return includeSubcategories; - } - - public void setIncludeSubcategories(boolean includeSubcategories) - { - this.includeSubcategories = includeSubcategories; - } - - public SearchContext generateCategorySearchContext() - { - SearchContext categorySearch = new SearchContext(); - - String[] categories = new String[1]; - categories[0] = SearchContext.getPathFromSpaceRef(currentCategory, includeSubcategories); - - categorySearch.setText(""); - categorySearch.setCategories(categories); - - return categorySearch; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/ErrorBean.java b/war/src/main/java/org/alfresco/web/bean/ErrorBean.java deleted file mode 100644 index d60aa6953a..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/ErrorBean.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean; - -import java.io.Serializable; - -import javax.servlet.ServletException; - -/** - * Bean used by the error page, holds the last exception to be thrown by the system - * - * @author gavinc - */ -public class ErrorBean implements Serializable -{ - private static final long serialVersionUID = -5101720299256547100L; - - public static final String ERROR_BEAN_NAME = "alfresco.ErrorBean"; - - private String returnPage; - private Throwable lastError; - private String errorMessageKey; - - /** - * @return Returns the page to go back to after the error has been displayed - */ - public String getReturnPage() - { - return returnPage; - } - - /** - * @param returnPage The page to return to after showing the error - */ - public void setReturnPage(String returnPage) - { - this.returnPage = returnPage; - } - - /** - * @return Returns the lastError. - */ - public Throwable getLastError() - { - return lastError; - } - - /** - * @param error The lastError to set. - */ - public void setLastError(Throwable error) - { - // servlet exceptions hide the actual error within the rootCause - // variable, set the base error to that and throw away the - // ServletException wrapper - if (error instanceof ServletException && - ((ServletException)error).getRootCause() != null) - { - this.lastError = ((ServletException)error).getRootCause(); - } - else - { - this.lastError = error; - } - this.errorMessageKey = null; - } - - /** - * Gets the error message key. - * - * @return the error message key - */ - public String getErrorMessageKey() - { - return errorMessageKey; - } - - /** - * Sets the error message key. - * - * @param errorMessageKey - * the new error message key - */ - public void setErrorMessageKey(String errorMessageKey) - { - this.errorMessageKey = errorMessageKey; - this.lastError = null; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/FileUploadBean.java b/war/src/main/java/org/alfresco/web/bean/FileUploadBean.java deleted file mode 100644 index 0b5d0fdbde..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/FileUploadBean.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean; - -import java.io.File; -import java.io.Serializable; - -/** - * Bean to hold the results of a file upload - * - * @author gavinc - */ -public final class FileUploadBean implements Serializable -{ - - private static final long serialVersionUID = 7667383955924957544L; - - public static final String FILE_UPLOAD_BEAN_NAME = "alfresco.UploadBean"; - - public static String getKey(final String id) - { - return ((id == null || id.length() == 0) - ? FILE_UPLOAD_BEAN_NAME - : FILE_UPLOAD_BEAN_NAME + "-" + id); - } - - private File file; - private String fileName; - private String filePath; - - /** - * @return Returns the file - */ - public File getFile() - { - return file; - } - - /** - * @param file The file to set - */ - public void setFile(File file) - { - this.file = file; - } - - /** - * @return Returns the name of the file uploaded - */ - public String getFileName() - { - return fileName; - } - - /** - * @param fileName The name of the uploaded file - */ - public void setFileName(String fileName) - { - this.fileName = fileName; - } - - /** - * @return Returns the path of the file uploaded - */ - public String getFilePath() - { - return filePath; - } - - /** - * @param filePath The file path of the uploaded file - */ - public void setFilePath(String filePath) - { - this.filePath = filePath; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/LinkPropertiesDialog.java b/war/src/main/java/org/alfresco/web/bean/LinkPropertiesDialog.java deleted file mode 100644 index 38df0ad7f0..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/LinkPropertiesDialog.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Iterator; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.dictionary.DataTypeDefinition; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.Utils.URLMode; - -/** - * Backing bean for the edit link properties dialog - * - * @author kevinr - * @author YanO - */ -public class LinkPropertiesDialog extends BaseDialogBean -{ - private static final long serialVersionUID = -167326851073011187L; - - private Node editableNode = null; - - - @Override - public void init(Map parameters) - { - super.init(parameters); - - // reset node instance for next dialog invocation - this.editableNode = null; - } - - public Map getProperties() - { - return getEditableNode().getProperties(); - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - /** - * Returns the node being edited - * - * @return The node being edited - */ - public Node getEditableNode() - { - if (this.editableNode == null) - { - if (this.parameters.containsKey("nodeRef")) - { - this.editableNode = new Node(new NodeRef(this.parameters.get("nodeRef"))); - } - else - { - throw new IllegalArgumentException("Dialog has not been initialised with noderef or setup action event called."); - } - } - return this.editableNode; - } - - /** - * Event handler called to setup the link object for property editing - * - * @param event The event - */ - public void setupFileLinkForAction(ActionEvent event) - { - this.editableNode = new Node(this.browseBean.getDocument().getNodeRef()); - } - - /** - * Event handler called to setup the link object for property editing - * - * @param event The event - */ - public void setupFolderLinkForAction(ActionEvent event) - { - this.editableNode = new Node(this.browseBean.getActionSpace().getNodeRef()); - } - - /** - * @return Human readable version of the Path to the destination object - */ - public String getDestinationPath() - { - NodeRef destRef = (NodeRef)getEditableNode().getProperties().get(ContentModel.PROP_LINK_DESTINATION); - return Repository.getNamePath( - this.getNodeService(), this.getNodeService().getPath(destRef), null, "/", null); - } - - /** - * Returns the URL to access the details page for the current document link object - * - * @return The bookmark URL - */ - public String getFileLinkBookmarkUrl() - { - NodeRef destRef = (NodeRef)this.browseBean.getDocument().getProperties().get(ContentModel.PROP_LINK_DESTINATION); - return Utils.generateURL(FacesContext.getCurrentInstance(), new Node(destRef), URLMode.SHOW_DETAILS); - } - - /** - * Returns the URL to access the details page for the current document link object - * - * @return The bookmark URL - */ - public String getSpaceLinkDestinationUrl() - { - NodeRef destRef = (NodeRef)this.browseBean.getActionSpace().getProperties().get(ContentModel.PROP_LINK_DESTINATION); - return Utils.generateURL(FacesContext.getCurrentInstance(), new Node(destRef), URLMode.SHOW_DETAILS); - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - try - { - NodeRef nodeRef = getEditableNode().getNodeRef(); - Map props = getEditableNode().getProperties(); - - //get the name and move the node as necessary - String name = (String) props.get(ContentModel.PROP_NAME); - if (name != null) - { - getFileFolderService().rename(nodeRef, name); - } - - Map properties = this.getNodeService().getProperties(nodeRef); - - // we need to put all the properties from the editable bag back into - // the format expected by the repository - - // deal with adding the "titled" aspect if required - String title = (String)props.get(ContentModel.PROP_TITLE); - String description = (String)props.get(ContentModel.PROP_DESCRIPTION); - if (title != null || description != null) - { - // add the aspect to be sure it's present - getNodeService().addAspect(nodeRef, ContentModel.ASPECT_TITLED, null); - // other props will get added later in setProperties() - } - - // add the remaining properties - Iterator iterProps = props.keySet().iterator(); - while (iterProps.hasNext()) - { - String propName = iterProps.next(); - QName qname = QName.createQName(propName); - - // make sure the property is represented correctly - Serializable propValue = (Serializable)props.get(propName); - - // check for empty strings when using number types, set to null in this case - if ((propValue != null) && (propValue instanceof String) && - (propValue.toString().length() == 0)) - { - PropertyDefinition propDef = this.getDictionaryService().getProperty(qname); - if (propDef != null) - { - if (propDef.getDataType().getName().equals(DataTypeDefinition.DOUBLE) || - propDef.getDataType().getName().equals(DataTypeDefinition.FLOAT) || - propDef.getDataType().getName().equals(DataTypeDefinition.INT) || - propDef.getDataType().getName().equals(DataTypeDefinition.LONG)) - { - propValue = null; - } - } - } - - properties.put(qname, propValue); - } - - // send the properties back to the repository - this.getNodeService().setProperties(nodeRef, properties); - } - catch (InvalidNodeRefException err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - context, Repository.ERROR_NODEREF), new Object[] {this.browseBean.getDocument().getId()})); - - // this failure means the node no longer exists - we cannot show the doc properties screen - outcome = AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME + - AlfrescoNavigationHandler.OUTCOME_SEPARATOR + "browse"; - } - catch (Throwable e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - context, Repository.ERROR_GENERIC), e.getMessage()), e); - outcome = null; - ReportedException.throwIfNecessary(e); - } - - return outcome; - } - - @Override - protected String doPostCommitProcessing(FacesContext context, String outcome) - { - if (this.browseBean.getDocument() != null) - { - this.browseBean.getDocument().reset(); - } - else if (this.browseBean.getActionSpace() != null) - { - this.browseBean.getActionSpace().reset(); - } - - return outcome; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/LoginBean.java b/war/src/main/java/org/alfresco/web/bean/LoginBean.java deleted file mode 100644 index bf90f475f3..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/LoginBean.java +++ /dev/null @@ -1,559 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean; - -import java.io.IOException; -import java.io.Serializable; -import java.io.StringWriter; -import java.text.MessageFormat; -import java.util.Locale; -import java.util.Map; - -import javax.faces.application.FacesMessage; -import javax.faces.component.UIComponent; -import javax.faces.component.UIInput; -import javax.faces.context.FacesContext; -import javax.faces.validator.ValidatorException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.security.authentication.AuthenticationDisallowedException; -import org.alfresco.repo.security.authentication.AuthenticationException; -import org.alfresco.repo.security.authentication.AuthenticationMaxUsersException; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.security.AuthenticationService; -import org.alfresco.service.cmr.security.PersonService; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.servlet.AuthenticationHelper; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.repository.User; -import org.alfresco.web.bean.users.UserPreferencesBean; -import org.alfresco.web.bean.users.UsersDialog; -import org.alfresco.web.ui.common.PanelGenerator; -import org.alfresco.web.ui.common.Utils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * JSF Managed Bean. Backs the "login.jsp" view to provide the form fields used - * to enter user data for login. Also contains bean methods to validate form - * fields and action event fired in response to the Login button being pressed. - * - * @author Kevin Roast - */ -public class LoginBean implements Serializable -{ - /** - * The default outcome of the logout action. - */ - private static final String OUTCOME_LOGOUT = "logout"; - - /** - * The outcome of the logout action when the user has been signed on by SSO. - */ - private static final String OUTCOME_RELOGIN = "relogin"; - - /** - * The name of the form parameter carrying the outcome to the logout action. - */ - private static final String PARAM_OUTCOME = "outcome"; - - /** flag to set in the user Session when an external authentication mechanism is used - * this informs the framework that user cannot Change Password or Logout in the usual way */ - private static final String SESSION_ATTRIBUTE_EXTERNAL_AUTH= "_alfExternalAuth"; - - private static final long serialVersionUID = 7417882503323795282L; - - /** - * @param authenticationService The AuthenticationService to set. - */ - public void setAuthenticationService(AuthenticationService authenticationService) - { - this.authenticationService = authenticationService; - } - - protected AuthenticationService getAuthenticationService() - { - if (authenticationService == null) - authenticationService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getAuthenticationService(); - return authenticationService; - } - - /** - * @param personService The personService to set. - */ - public void setPersonService(PersonService personService) - { - this.personService = personService; - } - - protected PersonService getPersonService() - { - if (personService == null) - personService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPersonService(); - return personService; - } - - /** - * @param nodeService The nodeService to set. - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - protected NodeService getNodeService() - { - if (nodeService == null) - nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - return nodeService; - } - - /** - * @param browseBean The BrowseBean to set. - */ - public void setBrowseBean(BrowseBean browseBean) - { - this.browseBean = browseBean; - } - - /** - * @param navigator The NavigationBean to set. - */ - public void setNavigator(NavigationBean navigator) - { - this.navigator = navigator; - } - - /** - * @param preferences The UserPreferencesBean to set - */ - public void setUserPreferencesBean(UserPreferencesBean preferences) - { - this.preferences = preferences; - } - - public UserPreferencesBean getUserPreferencesBean() - { - return preferences; - } - - /** - * @return "logout" if the default Alfresco authentication process is being used, else "relogin" - * if an external authorisation mechanism is present. - */ - public String getLogoutOutcome() - { - Map session = FacesContext.getCurrentInstance().getExternalContext().getSessionMap(); - return session.get(LOGIN_EXTERNAL_AUTH) == null ? OUTCOME_LOGOUT : OUTCOME_RELOGIN; - } - - /** - * @param val Username from login dialog - */ - public void setUsername(String val) - { - if ( val != null ) { val = val.trim(); } - this.username = val; - } - - /** - * @return The username string from login dialog - */ - public String getUsername() - { - // this value may have been set by a servlet filter via a cookie - // check for this by detecting a special value in the session - FacesContext context = FacesContext.getCurrentInstance(); - Map session = context.getExternalContext().getSessionMap(); - - String username = (String)session.get(AuthenticationHelper.SESSION_USERNAME); - if (username != null) - { - session.remove(AuthenticationHelper.SESSION_USERNAME); - this.username = username; - } - - return this.username; - } - - public String getUsernameInternal() - { - return this.username; - } - - /** - * @param val Password from login dialog - */ - public void setPassword(String val) - { - this.password = val; - } - - /** - * @return The password string from login dialog - */ - public String getPassword() - { - return this.password; - } - - /** - * @return true to display language selection, false to - */ - public boolean isLanguageSelect() - { - return Application.getClientConfig(FacesContext.getCurrentInstance()).isLanguageSelect(); - } - - /** - * Returns the HTML to display if the system is in TEAM mode - * - * @return The HTML to display - */ - public String getTeamLoginWarningHTML() - { - FacesContext context = FacesContext.getCurrentInstance(); - String contextPath = context.getExternalContext().getRequestContextPath(); - StringBuilder html = new StringBuilder(); - - try - { - html.append(""); - - StringWriter writer = new StringWriter(); - PanelGenerator.generatePanelStart(writer, contextPath, "yellowInner", "#ffffcc"); - html.append(writer.toString()); - - html.append(""); - html.append(""); - html.append("
"); - html.append(""); - html.append(Application.getMessage(context, "team_login_warning")); - html.append("
"); - - writer = new StringWriter(); - PanelGenerator.generatePanelEnd(writer, contextPath, "yellowInner"); - html.append(writer.toString()); - - html.append(""); - } - catch (IOException ioe) - { - logger.error(ioe); - } - - return html.toString(); - } - - // ------------------------------------------------------------------------------ - // Validator methods - - /** - * Validate that field "confirm" matches to the field "password" - */ - public void validateMatch(FacesContext context, UIComponent component, Object value) - throws ValidatorException - { - String confirm = (String)value; - - String field1Id = (String) component.getAttributes().get("passwd1Id"); - UIInput passComponent = (UIInput) context.getViewRoot().findComponent(field1Id); - String pass = (String) passComponent.getSubmittedValue(); - if (pass == null) - { - pass = (String) passComponent.getValue(); - } - - if (!pass.equals(confirm)) - { - String err = Application.getMessage(context, UsersDialog.ERROR_PASSWORD_MATCH); - throw new ValidatorException(new FacesMessage(err)); - } - } - - /** - * Validate password field data is acceptable - */ - public void validatePassword(FacesContext context, UIComponent component, Object value) - throws ValidatorException - { - int minPasswordLength = Application.getClientConfig(context).getMinPasswordLength(); - int maxPasswordLength = Application.getClientConfig(context).getMaxPasswordLength(); - - String pass = (String)value; - if (pass.length() < minPasswordLength || pass.length() > maxPasswordLength) - { - String err = MessageFormat.format(Application.getMessage(context, MSG_PASSWORD_LENGTH), - new Object[]{minPasswordLength, maxPasswordLength}); - throw new ValidatorException(new FacesMessage(err)); - } - } - - /** - * Validate Username field data is acceptable - */ - public void validateUsername(FacesContext context, UIComponent component, Object value) - throws ValidatorException - { - int minUsernameLength = Application.getClientConfig(context).getMinUsernameLength(); - - String name = ((String)value).trim(); - - if (name.length() < minUsernameLength || name.length() > 256) - { - String err = MessageFormat.format(Application.getMessage(context, MSG_USERNAME_LENGTH), - new Object[]{minUsernameLength, 256}); - throw new ValidatorException(new FacesMessage(err)); - } - if (name.indexOf('"') != -1) - { - String err = MessageFormat.format(Application.getMessage(context, MSG_USER_ERR), - new Object[]{"\""}); - throw new ValidatorException(new FacesMessage(err)); - } - } - - - // ------------------------------------------------------------------------------ - // Action event methods - - /** - * Login action handler - * - * @return outcome view name - */ - public String login() - { - String outcome = null; - - FacesContext fc = FacesContext.getCurrentInstance(); - - if (this.username != null && this.username.length() != 0 && - this.password != null && this.password.length() != 0) - { - try - { - // Perform a full session invalidation to ensure no cached data is left around - // - important if the login page has been accessed directly rather than via the Login/out action links - logout(); - - // Authenticate via the authentication service, then save the details of user in an object - // in the session - this is used by the servlet filter etc. on each page to check for login - this.getAuthenticationService().authenticate(this.username, this.password.toCharArray()); - - // Set the user name as stored by the back end - this.username = this.getAuthenticationService().getCurrentUserName(); - - // setup User object and Home space ID - User user = new User( - this.username, - this.getAuthenticationService().getCurrentTicket(), - getPersonService().getPerson(this.username)); - - NodeRef homeSpaceRef = (NodeRef) this.getNodeService().getProperty(getPersonService().getPerson(this.username), ContentModel.PROP_HOMEFOLDER); - - // check that the home space node exists - else user cannot login - if (homeSpaceRef == null || this.getNodeService().exists(homeSpaceRef) == false) - { - throw new InvalidNodeRefException(homeSpaceRef); - } - user.setHomeSpaceId(homeSpaceRef.getId()); - - // put the User object in the Session - the authentication servlet will then allow - // the app to continue without redirecting to the login page - Application.setCurrentUser(fc, user); - - // Save the current username to cookie - AuthenticationHelper.setUsernameCookie((HttpServletRequest) fc.getExternalContext().getRequest(),(HttpServletResponse) fc.getExternalContext().getResponse(), this.username); - - // Programatically retrieve the LoginOutcomeBean from JSF - LoginOutcomeBean loginOutcomeBean = (LoginOutcomeBean) fc.getApplication().createValueBinding( - "#{LoginOutcomeBean}").getValue(fc); - - // if a redirect URL has been provided then use that - // this allows servlets etc. to provide a URL to return too after a successful login - String redirectURL = loginOutcomeBean.getRedirectURL(); - - // ALF-10312: Validate we are redirecting within this web app - if (redirectURL != null && !redirectURL.isEmpty() && !redirectURL.startsWith(fc.getExternalContext().getRequestContextPath())) - { - if (logger.isWarnEnabled()) - logger.warn("Security violation. Unable to redirect to external location: " + redirectURL); - redirectURL = null; - } - - if (redirectURL != null && redirectURL.length() > 0) - { - if (logger.isDebugEnabled()) - logger.debug("Redirect URL found: " + redirectURL); - - try - { - fc.getExternalContext().redirect(redirectURL); - fc.responseComplete(); - return null; - } - catch (IOException ioErr) - { - logger.warn("Unable to redirect to url: " + redirectURL, ioErr); - } - } - else - { - // special case to handle jump to My Alfresco page initially - - // note: to enable MT runtime client config customization, need to re-init NavigationBean - // in context of tenant login page - this.navigator.initFromClientConfig(); - - if (NavigationBean.LOCATION_MYALFRESCO.equals(this.preferences.getStartLocation())) - { - return "myalfresco"; - } - else - { - // generally this will navigate to the generic browse screen - return "success"; - } - } - } - catch (AuthenticationDisallowedException aerr) - { - Utils.addErrorMessage(Application.getMessage(fc, MSG_ERROR_LOGIN_DISALLOWED)); - } - catch (AuthenticationMaxUsersException aerr) - { - Utils.addErrorMessage(Application.getMessage(fc, MSG_ERROR_LOGIN_MAXUSERS)); - } - catch (AuthenticationException aerr) - { - Utils.addErrorMessage(Application.getMessage(fc, MSG_ERROR_UNKNOWN_USER)); - } - catch (InvalidNodeRefException refErr) - { - String msg; - if (refErr.getNodeRef() != null) - { - msg = refErr.getNodeRef().toString(); - } - else - { - msg = Application.getMessage(fc, MSG_NONE); - } - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(fc, - Repository.ERROR_NOHOME), msg)); - } - } - else - { - Utils.addErrorMessage(Application.getMessage(fc, MSG_ERROR_MISSING)); - } - - return outcome; - } - - /** - * Invalidate ticket and logout user - */ - public String logout() - { - FacesContext context = FacesContext.getCurrentInstance(); - - // The outcome is decided in advance (before session expiry) and included as a parameter - Map params = context.getExternalContext().getRequestParameterMap(); - String outcome = (String)params.get(PARAM_OUTCOME); - if (outcome == null) - { - outcome = OUTCOME_LOGOUT; - } - - Locale language = Application.getLanguage(context); - - // Perform log out actions - Application.logOut(context); - - // set language to last used on the login page - Application.setLanguage(context, language.toString()); - - return outcome; - } - - public boolean getIsExternalAuthentication() - { - HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); - return (request.getSession().getAttribute(SESSION_ATTRIBUTE_EXTERNAL_AUTH) != null); - } - - // ------------------------------------------------------------------------------ - // Private data - - private static final Log logger = LogFactory.getLog(LoginBean.class); - - /** I18N messages */ - private static final String MSG_ERROR_MISSING = "error_login_missing"; - private static final String MSG_ERROR_UNKNOWN_USER = "error_login_user"; - private static final String MSG_ERROR_LOGIN_DISALLOWED = "error_login_disallowed"; - private static final String MSG_ERROR_LOGIN_MAXUSERS = "error_login_maxusers"; - private static final String MSG_NONE = "none"; - - public static final String MSG_ERROR_LOGIN_NOPERMISSIONS = "login_err_permissions"; - public static final String MSG_USERNAME_LENGTH = "login_err_username_length"; - public static final String MSG_PASSWORD_LENGTH = "login_err_password_length"; - public static final String MSG_USER_ERR = "user_err_user_name"; - - public static final String LOGIN_EXTERNAL_AUTH = "_alfExternalAuth"; - public static final String LOGIN_NOPERMISSIONS = "_alfNoPermissions"; - - /** user name */ - private String username = null; - - /** password */ - private String password = null; - - /** PersonService bean reference */ - private transient PersonService personService; - - /** AuthenticationService bean reference */ - private transient AuthenticationService authenticationService; - - /** NodeService bean reference */ - private transient NodeService nodeService; - - /** The BrowseBean reference */ - protected BrowseBean browseBean; - - /** The NavigationBean bean reference */ - protected NavigationBean navigator; - - /** The user preferences bean reference */ - protected UserPreferencesBean preferences; -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/bean/LoginOutcomeBean.java b/war/src/main/java/org/alfresco/web/bean/LoginOutcomeBean.java deleted file mode 100644 index e85551821d..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/LoginOutcomeBean.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean; - -import java.io.Serializable; - -/** - * A request-scoped bean that is used to propagate the URL to redirect to after successful login. This is now done with - * request parameters rather than session-scoped beans so that tools such as MS Office, which do not propagate cookies - * to hyperlinks, can be used to open hyperlinks to protected documents (ALF-206). - * - * @author dward - */ -public class LoginOutcomeBean implements Serializable -{ - /** The name of the request parameter that provides the initial value of the {@link #redirectURL} property. */ - public static final String PARAM_REDIRECT_URL = "_alfRedirect"; - - private static final long serialVersionUID = -2575348340143674698L; - - /** The URL to redirect to after successful login. */ - private String redirectURL; - - /** - * Gets the URL to redirect to after successful login. - * - * @return the URL to redirect to after successful login - */ - public String getRedirectURL() - { - return redirectURL; - } - - /** - * Sets the URL to redirect to after successful login. - * - * @param redirectURL - * the URL to redirect to after successful login - */ - public void setRedirectURL(String redirectURL) - { - this.redirectURL = redirectURL; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/MultiValueEditorBean.java b/war/src/main/java/org/alfresco/web/bean/MultiValueEditorBean.java deleted file mode 100644 index b30ea17180..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/MultiValueEditorBean.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -/** - * Helper bean used to temporarily store the last item added in a multi - * value editor component. - * - * A Map is used so that multiple components on the same page can use the - * same backing bean. - * - * @author gavinc - */ -public class MultiValueEditorBean implements Serializable -{ - private static final long serialVersionUID = -5180578793877515158L; - - private Map lastItemsAdded = new HashMap(10); - - public Map getLastItemsAdded() - { - return lastItemsAdded; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/NavigationBean.java b/war/src/main/java/org/alfresco/web/bean/NavigationBean.java deleted file mode 100644 index c8009e8da0..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/NavigationBean.java +++ /dev/null @@ -1,1255 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.filesys.repo.ContentDiskInterface; -import org.alfresco.jlan.server.config.ServerConfigurationAccessor; -import org.alfresco.jlan.server.filesys.DiskSharedDevice; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork; -import org.alfresco.repo.security.permissions.AccessDeniedException; -import org.alfresco.repo.tenant.TenantService; -import org.alfresco.repo.web.scripts.FileTypeImageUtils; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.admin.RepoAdminService; -import org.alfresco.service.cmr.admin.RepoUsage; -import org.alfresco.service.cmr.repository.FileTypeImageSize; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.repository.StoreRef; -import org.alfresco.service.cmr.repository.TemplateImageResolver; -import org.alfresco.service.cmr.repository.TemplateService; -import org.alfresco.service.cmr.rule.RuleService; -import org.alfresco.service.cmr.search.SearchService; -import org.alfresco.service.cmr.security.AccessStatus; -import org.alfresco.service.cmr.security.MutableAuthenticationService; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.descriptor.Descriptor; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.repository.User; -import org.alfresco.web.bean.search.SearchContext; -import org.alfresco.web.bean.spaces.CreateSpaceWizard; -import org.alfresco.web.bean.spaces.SpaceDetailsDialog; -import org.alfresco.web.bean.users.UserPreferencesBean; -import org.alfresco.web.config.ClientConfigElement; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.Utils.URLMode; -import org.alfresco.web.ui.common.component.IBreadcrumbHandler; -import org.alfresco.web.ui.common.component.UIBreadcrumb; -import org.alfresco.web.ui.common.component.UIModeList; -import org.alfresco.web.ui.repo.component.IRepoBreadcrumbHandler; -import org.alfresco.web.ui.repo.component.shelf.UIShelf; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.web.jsf.FacesContextUtils; - -/** - * Bean providing access and management of the various global navigation mechanisms - * such as the My Home, Company Home, Guest Home toolbar shortcuts, breadcrumb and - * the current node id and associated properties. - * - * @author Kevin Roast - */ -public class NavigationBean implements Serializable -{ - private static final long serialVersionUID = -648110889585522227L; - - /** Public JSF Bean name */ - public static final String BEAN_NAME = "NavigationBean"; - - private static Log logger = LogFactory.getLog(NavigationBean.class); - - /** - * Default constructor - */ - public NavigationBean() - { - initFromClientConfig(); - } - - - // ------------------------------------------------------------------------------ - // Bean property getters and setters - - /** - * @param nodeService The nodeService to set. - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - protected NodeService getNodeService() - { - if (nodeService == null) - nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - return nodeService; - } - - /** - * @param searchService The searchService to set. - */ - public void setSearchService(SearchService searchService) - { - this.searchService = searchService; - } - - protected SearchService getSearchService() - { - if (searchService == null) - this.searchService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getSearchService(); - return searchService; - } - - /** - * @param namespaceService The namespaceService to set. - */ - public void setNamespaceService(NamespaceService namespaceService) - { - this.namespaceService = namespaceService; - } - - protected NamespaceService getNamespaceService() - { - if (namespaceService == null) - this.namespaceService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNamespaceService(); - return namespaceService; - } - - public void setRepoAdminService(RepoAdminService repoAdminService) - { - this.repoAdminService = repoAdminService; - } - - - public RepoAdminService getRepoAdminService() - { - if (repoAdminService == null) - { - this.repoAdminService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getRepoAdminService(); - } - return repoAdminService; - } - - /** - * @param ruleService The ruleService to use - */ - public void setRuleService(RuleService ruleService) - { - this.ruleService = ruleService; - } - - protected RuleService getRuleService() - { - if (ruleService == null) - this.ruleService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getRuleService(); - return ruleService; - } - - /** - * @param serverConfiguration The serverConfiguration to set. - */ - public void setServerConfiguration(ServerConfigurationAccessor serverConfiguration) - { - this.serverConfiguration = serverConfiguration; - } - - protected ServerConfigurationAccessor getServerConfiguration() - { - if (serverConfiguration == null) - this.serverConfiguration = (ServerConfigurationAccessor) FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), "fileServerConfiguration"); - return serverConfiguration; - } - - /** - * @param contentDiskDriver The contentDiskDriver to set. - */ - public void setContentDiskDriver(ContentDiskInterface contentDiskDriver) - { - this.contentDiskDriver = contentDiskDriver; - } - - protected ClientConfigElement getClientConfig() - { - if (clientConfig == null) - this.clientConfig = Application.getClientConfig(FacesContext.getCurrentInstance()); - return clientConfig; - } - - /** - * @param preferences The UserPreferencesBean to set - */ - public void setUserPreferencesBean(UserPreferencesBean preferences) - { - this.preferences = preferences; - } - - /** - * @param authService The AuthenticationService to set. - */ - public void setAuthenticationService(MutableAuthenticationService authService) - { - this.authService = authService; - } - - protected MutableAuthenticationService getAuthService() - { - if (authService == null) - this.authService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getAuthenticationService(); - return authService; - } - - /** - * @param permissionService The PermissionService to set. - */ - public void setPermissionService(PermissionService permissionService) - { - this.permissionService = permissionService; - } - - protected PermissionService getPermissionService() - { - if (permissionService == null) - this.permissionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPermissionService(); - return permissionService; - } - - /** - * @return the User object representing the current instance for this user - */ - public User getCurrentUser() - { - return Application.getCurrentUser(FacesContext.getCurrentInstance()); - } - - /** - * @return true if the system is running within a JSR-168 portal container - */ - public boolean getInPortalServer() - { - return Application.inPortalServer(); - } - - /** - * Return the expanded state of the Shelf panel wrapper component - * - * @return the expanded state of the Shelf panel wrapper component - */ - public boolean isShelfExpanded() - { - return this.shelfExpanded; - } - - /** - * Set the expanded state of the Shelf panel wrapper component - * - * @param expanded true to expanded the Shelf panel area, false to hide it - */ - public void setShelfExpanded(boolean expanded) - { - this.shelfExpanded = expanded; - } - - /** - * Return the width of the main work area depending on the visibility of the Shelf panel - * - * @return width, which will either be "80%" or "100%" - */ - public String getWorkAreaWidth() - { - return this.shelfExpanded ? "80%" : "100%"; - } - - /** - * @return Returns the array containing the expanded state of the shelf items - */ - public boolean[] getShelfItemExpanded() - { - return this.shelfItemExpanded; - } - - /** - * @param shelfItemExpanded The array containing the expanded state of the shelf items - */ - public void setShelfItemExpanded(boolean[] shelfItemExpanded) - { - this.shelfItemExpanded = shelfItemExpanded; - } - - /** - * @return Returns the toolbar Location - initially set from the user preferences. - */ - public String getToolbarLocation() - { - if (this.toolbarLocation == null) - { - // if the toolbar location has not been set yet, try and get the - // default via the user preferences object - this.toolbarLocation = this.preferences.getStartLocation(); - - // test that the user still has access to the specified location - // the location will need to be reset if the user permissions are no longer valid - if (NavigationBean.LOCATION_COMPANY.equals(this.toolbarLocation)) - { - if (getCompanyHomeVisible() == false) - { - this.toolbarLocation = null; - } - } - else if (NavigationBean.LOCATION_GUEST.equals(this.toolbarLocation)) - { - if (getGuestHomeVisible() == false) - { - this.toolbarLocation = null; - } - } - - // if don't have a valid start location default to My Home - if (this.toolbarLocation == null) - { - this.toolbarLocation = LOCATION_HOME; - this.preferences.setStartLocation(this.toolbarLocation); - } - } - - return this.toolbarLocation; - } - - /** - * @param location The toolbar Location to set. - */ - public void setToolbarLocation(String location) - { - this.toolbarLocation = location; - } - - /** - * Process the selected toolbar location. Setup the breadcrumb with initial value and - * setup the current node ID. This method can also perform the navigatin setup if requested. - * - * @param location Toolbar location constant - * @param navigate True to perform navigation, false otherwise - */ - @SuppressWarnings("serial") - public void processToolbarLocation(String location, boolean navigate) - { - this.toolbarLocation = location; - - FacesContext context = FacesContext.getCurrentInstance(); - if (LOCATION_COMPANY.equals(location)) - { - List elements = new ArrayList(1); - Node companyHome = getCompanyHomeNode(); - elements.add(new NavigationBreadcrumbHandler(companyHome.getNodeRef(), companyHome.getName())); - setLocation(elements); - setCurrentNodeId(companyHome.getId()); - - if (s_logger.isDebugEnabled()) - s_logger.debug("Created breadcrumb for companyhome: " + elements); - - // inform registered beans that the current area has changed - UIContextService.getInstance(FacesContext.getCurrentInstance()).areaChanged(); - - // we need to force a navigation to refresh the browse screen breadcrumb - if (navigate) - { - context.getApplication().getNavigationHandler().handleNavigation(context, null, OUTCOME_BROWSE); - } - } - else if (LOCATION_HOME.equals(location)) - { - List elements = new ArrayList(1); - String homeSpaceId = Application.getCurrentUser(context).getHomeSpaceId(); - NodeRef homeSpaceRef = new NodeRef(Repository.getStoreRef(), homeSpaceId); - - if (this.clientConfig.getBreadcrumbMode().equals(ClientConfigElement.BREADCRUMB_LOCATION)) - { - Repository.setupBreadcrumbLocation(context, this, elements, homeSpaceRef); - - if (s_logger.isDebugEnabled()) - s_logger.debug("Created breadcrumb location for userhome: " + elements); - } - else - { - String homeSpaceName = Repository.getNameForNode(this.getNodeService(), homeSpaceRef); - elements.add(new NavigationBreadcrumbHandler(homeSpaceRef, homeSpaceName)); - - if (s_logger.isDebugEnabled()) - s_logger.debug("Created breadcrumb path for userhome: " + elements); - } - - setLocation(elements); - setCurrentNodeId(homeSpaceRef.getId()); - - // inform registered beans that the current area has changed - UIContextService.getInstance(FacesContext.getCurrentInstance()).areaChanged(); - - // we need to force a navigation to refresh the browse screen breadcrumb - if (navigate) - { - context.getApplication().getNavigationHandler().handleNavigation(context, null, OUTCOME_BROWSE); - } - } - else if (LOCATION_GUEST.equals(location)) - { - List elements = new ArrayList(1); - Node guestHome = getGuestHomeNode(); - - if (this.clientConfig.getBreadcrumbMode().equals(ClientConfigElement.BREADCRUMB_LOCATION)) - { - Repository.setupBreadcrumbLocation(context, this, elements, guestHome.getNodeRef()); - - if (s_logger.isDebugEnabled()) - s_logger.debug("Created breadcrumb location for guesthome: " + elements); - } - else - { - elements.add(new NavigationBreadcrumbHandler(guestHome.getNodeRef(), guestHome.getName())); - - if (s_logger.isDebugEnabled()) - s_logger.debug("Created breadcrumb path for guesthome: " + elements); - } - - setLocation(elements); - setCurrentNodeId(guestHome.getId()); - - // inform registered beans that the current area has changed - UIContextService.getInstance(FacesContext.getCurrentInstance()).areaChanged(); - - // we need to force a navigation to refresh the browse screen breadcrumb - if (navigate) - { - context.getApplication().getNavigationHandler().handleNavigation(context, null, OUTCOME_BROWSE); - } - } - else if (LOCATION_MYALFRESCO.equals(location)) - { - // make sure we set a current node ID as some screens expect this - if (getCurrentNodeId() == null) - { - String homeSpaceId = Application.getCurrentUser(context).getHomeSpaceId(); - NodeRef homeSpaceRef = new NodeRef(Repository.getStoreRef(), homeSpaceId); - setCurrentNodeId(homeSpaceRef.getId()); - } - - // create a breadcrumb handler for this special case location (not a node) - List elements = new ArrayList(1); - elements.add(new IBreadcrumbHandler() - { - @SuppressWarnings("unchecked") - public String navigationOutcome(UIBreadcrumb breadcrumb) - { - setLocation( (List)breadcrumb.getValue() ); - return OUTCOME_MYALFRESCO; - }; - - public String toString() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_MYALFRESCO); - }; - }); - - if (s_logger.isDebugEnabled()) - s_logger.debug("Created breadcrumb for myalfresco: " + elements); - - setLocation(elements); - - // inform registered beans that the current area has changed - UIContextService.getInstance(FacesContext.getCurrentInstance()).areaChanged(); - - // we need to force a navigation to refresh the browse screen breadcrumb - if (navigate) - { - context.getApplication().getNavigationHandler().handleNavigation(context, null, OUTCOME_MYALFRESCO); - } - } - else - { - // handle outcomes to any other custom location - context.getApplication().getNavigationHandler().handleNavigation(context, null, location); - } - } - - /** - * @return Returns the helpUrl. - */ - public String getHelpUrl() - { - return this.helpUrl; - } - - /** - * @param helpUrl The helpUrl to set. - */ - public void setHelpUrl(String helpUrl) - { - if (this.helpUrl == null) - { - Descriptor serverDescriptor = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getDescriptorService().getServerDescriptor(); - // search / replace each available key occurrence in the template string - // Note: server descriptor is looking for "version.major", "version.minor", etc. - Pattern p = Pattern.compile("\\{(\\w+\\.?\\w+)\\}"); - Matcher m = p.matcher(helpUrl); - boolean result = m.find(); - if (result) - { - StringBuffer sb = new StringBuffer(); - String value = null; - do - { - value = serverDescriptor.getDescriptor(m.group(1)); - m.appendReplacement(sb, value != null ? value : m.group(1)); - result = m.find(); - } while (result); - m.appendTail(sb); - helpUrl = sb.toString(); - } - - this.helpUrl = helpUrl; - } - } - - /** - * @return the number of rules associated with the current space - */ - public int getRuleCount() - { - Node node = getCurrentNode(); - return (node != null ? this.getRuleService().countRules(node.getNodeRef()) : 0); - } - - /** - * @return Returns the search context object if any. - */ - public SearchContext getSearchContext() - { - return this.searchContext; - } - - /** - * @param searchContext The search context object to set or null to clear search. - */ - public void setSearchContext(SearchContext searchContext) - { - this.searchContext = searchContext; - - UIContextService.getInstance(FacesContext.getCurrentInstance()).notifyBeans(); - } - - /** - * @return Returns the currently browsing node Id. - */ - public String getCurrentNodeId() - { - return this.currentNodeId; - } - - /** - * Set the node Id of the current folder/space container node. - *

- * Setting this value causes the UI to update and display the specified node as current. - * - * @param currentNodeId The currently browsing node Id. - */ - public void setCurrentNodeId(String currentNodeId) - { - if (s_logger.isDebugEnabled()) - s_logger.debug("Setting current node id to: " + currentNodeId); - - if (currentNodeId == null) - { - throw new AlfrescoRuntimeException("Can not set the current node id to null"); - } - - // set the current Node Id for our UI context operations - this.currentNodeId = currentNodeId; - - // clear other context that is based on or relevant to the Node id - this.currentNode = null; - this.searchContext = null; - - // inform any interested beans that the UI needs updating after this change - UIContextService.getInstance(FacesContext.getCurrentInstance()).notifyBeans(); - - // clear current node context after the notify - this is to ensure that if any delegates - // performed operations on the current node, that we have fresh data for the next View - this.currentNode = null; - } - - /** - * @return true if the current node has a custom view available - */ - public boolean getHasCustomView() - { - return getHasWebscriptView() || getHasTemplateView(); - } - - /** - * @return true if the current node has a Template based custom view available - */ - public boolean getHasTemplateView() - { - Node node = getCurrentNode(); - if (node.hasAspect(ContentModel.ASPECT_TEMPLATABLE)) - { - NodeRef templateRef = (NodeRef)node.getProperties().get(ContentModel.PROP_TEMPLATE); - return (templateRef != null && this.getNodeService().exists(templateRef) && - this.getPermissionService().hasPermission(templateRef, PermissionService.READ) == AccessStatus.ALLOWED); - } - return false; - } - - /** - * @return true if the current node has a Webscript based custom view available - */ - public boolean getHasWebscriptView() - { - Node node = getCurrentNode(); - if (node.hasAspect(ContentModel.ASPECT_WEBSCRIPTABLE)) - { - return (node.getProperties().get(ContentModel.PROP_WEBSCRIPT) != null); - } - return false; - } - - /** - * @return the NodeRef.toString() for the current node Template custom view if it has one - */ - public String getCurrentNodeTemplate() - { - NodeRef ref = (NodeRef)getCurrentNode().getProperties().get(ContentModel.PROP_TEMPLATE); - return ref != null ? ref.toString() : null; - } - - /** - * @return the service url for the current node Webscript custom view if it has one - */ - public String getCurrentNodeWebscript() - { - return (String)getCurrentNode().getProperties().get(ContentModel.PROP_WEBSCRIPT); - } - - /** - * Returns a model for use by a template on a space Dashboard page. - * - * @return model containing current current space info. - */ - @SuppressWarnings("unchecked") - public Map getTemplateModel() - { - HashMap model = new HashMap(2, 1.0f); - - model.put("space", getCurrentNode().getNodeRef()); - model.put(TemplateService.KEY_IMAGE_RESOLVER, - new TemplateImageResolver() - { - public String resolveImagePathForName(String filename, FileTypeImageSize size) - { - return FileTypeImageUtils.getFileTypeImage(FacesContext.getCurrentInstance(), filename, size); - } - }); - - return model; - } - - /** - * Clear state so that the current node properties cache for the next time they are requested - */ - public void resetCurrentNodeProperties() - { - this.currentNode = null; - } - - /** - * @return The Map of properties for the current Node. - */ - public Map getNodeProperties() - { - return getCurrentNode().getProperties(); - } - - /** - * @return The current Node object for UI context operations - */ - public Node getCurrentNode() - { - if (this.currentNode == null) - { - if (this.currentNodeId == null) - { - // handle the possibility that we have no current location - // this is possible in cluster fail-over or due to a missing node - // default back to the current toolbar root location - this.processToolbarLocation(this.getToolbarLocation(), false); - } - - if (s_logger.isDebugEnabled()) - s_logger.debug("Caching properties for node id: " + this.currentNodeId); - - NodeRef nodeRef; - Node node; - Map props; - try - { - // build a node which components on the JSP page can bind too - nodeRef = new NodeRef(Repository.getStoreRef(), this.currentNodeId); - node = new Node(nodeRef); - - // early init properties for this node (by getProperties() call) - // resolve icon in-case one has not been set - props = node.getProperties(); - } - catch (InvalidNodeRefException refErr) - { - FacesContext fc = FacesContext.getCurrentInstance(); - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - fc, ERROR_DELETED_FOLDER), new Object[] {this.currentNodeId}) ); - - nodeRef = new NodeRef(Repository.getStoreRef(), Application.getCompanyRootId(fc)); - node = new Node(nodeRef); - props = node.getProperties(); - } - String icon = (String)props.get("app:icon"); - props.put("icon", icon != null ? icon : CreateSpaceWizard.DEFAULT_SPACE_ICON_NAME); - String cifsPath = Utils.generateURL(FacesContext.getCurrentInstance(), node, URLMode.CIFS); - node.getProperties().put("cifsPath", cifsPath == null ? "" : cifsPath); - node.getProperties().put("cifsPathLabel", cifsPath == null ? "" : cifsPath.substring(8)); // strip file:/// part - this.currentNode = node; - } - - return this.currentNode; - } - - /** - * @return Boolean value according to CREATE_CHILDREN permission on the current node. - */ - public boolean isCreateChildrenPermissionEnabled() - { - return getCurrentNode().hasPermission(PermissionService.CREATE_CHILDREN); - } - - /** - * @return Returns the breadcrumb handler elements representing the location path of the UI. - */ - public List getLocation() - { - if (this.location == null) - { - // get the initial location from the user preferences - processToolbarLocation(getToolbarLocation(), false); - } - - return this.location; - } - - /** - * @param location The UI location representation to set. - */ - public void setLocation(List location) - { - this.location = location; - } - - /** - * @return true if we are currently the special Guest user - */ - public boolean getIsGuest() - { - return Repository.getIsGuest(FacesContext.getCurrentInstance()); - } - - /** - * Sets up the dispatch context so that the navigation handler knows - * what object is being acted upon - * - * @param node The node to be added to the dispatch context - */ - public void setupDispatchContext(Node node) - { - this.dispatchContext = node; - } - - /** - * Resets the dispatch context - */ - public void resetDispatchContext() - { - this.dispatchContext = null; - } - - /** - * Returns the node currently set in the dispatch context - * - * @return The node being dispatched or null if there is no - * dispatch context - */ - public Node getDispatchContextNode() - { - return this.dispatchContext; - } - - /** - * @return Node representing the Company Home folder - */ - public Node getCompanyHomeNode() - { - if (this.companyHomeNode == null) - { - FacesContext fc = FacesContext.getCurrentInstance(); - String companyRootId = Application.getCompanyRootId(fc); - if (companyRootId != null) - { - NodeRef companyRootRef = new NodeRef(Repository.getStoreRef(), companyRootId); - this.companyHomeNode = new Node(companyRootRef); - } - } - return this.companyHomeNode; - } - - /** - * @return Node representing the Guest Home Space folder - */ - public Node getGuestHomeNode() - { - if (this.guestHomeNode == null) - { - try - { - FacesContext fc = FacesContext.getCurrentInstance(); - String xpath = Application.getRootPath(fc) + "/" + Application.getGuestHomeFolderName(fc); - List guestHomeRefs = this.getSearchService().selectNodes( - this.getNodeService().getRootNode(Repository.getStoreRef()), - xpath, null, this.getNamespaceService(), false); - if (guestHomeRefs.size() == 1) - { - this.guestHomeNode = new Node(guestHomeRefs.get(0)); - } - } - catch (InvalidNodeRefException err1) - { - // cannot continue if this occurs - } - catch (AccessDeniedException err2) - { - // cannot see node if this occurs - } - } - return this.guestHomeNode; - } - - /** - * @return true if the Company home node is accessible to the current user - */ - public boolean getCompanyHomeVisible() - { - try - { - Node companyHomeNode = getCompanyHomeNode(); - if (companyHomeNode != null) - { - return companyHomeNode.hasPermission(PermissionService.READ); - } - else - { - return false; - } - } - catch (Throwable e) - { - if (logger.isDebugEnabled()) - { - logger.debug("getCompanyHomeVisible failed", e); - } - return false; - } - } - - /** - * @return true if the Guest home node is accessible to the current user - */ - public boolean getGuestHomeVisible() - { - try - { - if (this.getAuthService().guestUserAuthenticationAllowed()) - { - Node guestHome = getGuestHomeNode(); - return guestHome != null && guestHome.hasPermission(PermissionService.READ); - } - else - { - return false; - } - } - catch (Throwable e) - { - if (logger.isDebugEnabled()) - { - logger.debug("getGuestHomeVisible failed", e); - } - return false; - } - } - - - // ------------------------------------------------------------------------------ - // Navigation action event handlers - - /** - * Action handler to toggle the expanded state of the shelf. - * The panel component wrapping the shelf area of the UI is value bound to the shelfExpanded property. - */ - public void toggleShelf(ActionEvent event) - { - this.shelfExpanded = !this.shelfExpanded; - } - - /** - * Action handler called after a Shelf Group has had its expanded state toggled by the user - */ - public void shelfGroupToggled(ActionEvent event) - { - UIShelf.ShelfEvent shelfEvent = (UIShelf.ShelfEvent)event; - this.shelfItemExpanded[shelfEvent.Index] = shelfEvent.Expanded; - } - - /** - * Action to change the toolbar location - * Currently this will changed the location from Company to the users Home space - */ - public void toolbarLocationChanged(ActionEvent event) - { - FacesContext context = FacesContext.getCurrentInstance(); - try - { - UIModeList locationList = (UIModeList)event.getComponent(); - String location = locationList.getValue().toString(); - processToolbarLocation(location, true); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NOHOME), Application.getCurrentUser(context).getHomeSpaceId()), refErr ); - } - catch (Exception err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err); - } - } - - /** - * @param diskShare Filesystem shared device - * @return CIFS server path as network style string label - */ - public String getCIFSServerPath(DiskSharedDevice diskShare) - { - if (this.cifsServerPath == null) - { - StringBuilder buf = new StringBuilder(32); - - String serverName = this.getServerConfiguration().getServerName(); - if (serverName != null && serverName.length() != 0) - { - buf.append("\\\\"); - buf.append(serverName); - - // Check if there is a suffix to apply to the host name - if (clientConfig != null && clientConfig.getCifsURLSuffix() != null) - { - buf.append(clientConfig.getCifsURLSuffix()); - } - - buf.append("\\"); - buf.append(diskShare.getName()); - } - - this.cifsServerPath = buf.toString(); - } - - return this.cifsServerPath; - } - - /** - * @return true if the current space has an RSS feed applied - */ - public boolean isRSSFeed() - { - return SpaceDetailsDialog.hasRSSFeed(getCurrentNode()); - } - - /** - * @return RSS Feed URL for the current space - */ - public String getRSSFeedURL() - { - return SpaceDetailsDialog.buildRSSFeedURL(getCurrentNode()); - } - - /** - * @return true if User/Group admin is allowed by admin users - */ - public boolean isAllowUserGroupAdmin() - { - return this.clientConfig.isUserGroupAdmin(); - } - - /** - * @return true if users can configure their own settings in the User Console - */ - public boolean isAllowUserConfig() - { - return this.clientConfig.getAllowUserConfig(); - } - - /** - * @return true if a users can modify the password set against their authentication - */ - public boolean isAllowUserChangePassword() - { - return this.authService.isAuthenticationMutable(this.authService.getCurrentUserName()); - } - - /** - * @return true if this is a team license - */ - public boolean isTeamMode() - { - Boolean teamMode = AuthenticationUtil.runAs(new RunAsWork() - { - public Boolean doWork() throws Exception - { - RepoAdminService s = getRepoAdminService(); - - if (s != null) - { - if (RepoUsage.LicenseMode.TEAM.equals(s.getRestrictions().getLicenseMode())) - { - return Boolean.TRUE; - } - } - - return Boolean.FALSE; - } - }, AuthenticationUtil.getSystemUserName()); - - return teamMode.booleanValue(); - } - - - // ------------------------------------------------------------------------------ - // Helpers - - /** - * Initialise default values from client configuration - * - * Package visibility to allow LoginBean to re-init (for example, in context of tenant config) - */ - /* package */ void initFromClientConfig() - { - this.clientConfig = Application.getClientConfig(FacesContext.getCurrentInstance()); - this.setHelpUrl(clientConfig.getHelpUrl()); - this.shelfExpanded = clientConfig.isShelfVisible(); - } - - - // ------------------------------------------------------------------------------ - // Inner classes - - /** - * Class to handle breadcrumb interaction for top-level navigation pages - */ - public class NavigationBreadcrumbHandler implements IRepoBreadcrumbHandler - { - private static final long serialVersionUID = 4833194653193016638L; - - /** - * Constructor - * - * @param label Element label - */ - public NavigationBreadcrumbHandler(NodeRef ref, String label) - { - this.label = label; - this.ref = ref; - } - - /** - * @see java.lang.Object#toString() - */ - public String toString() - { - return this.label; - } - - /** - * @see org.alfresco.web.ui.common.component.IBreadcrumbHandler#navigationOutcome(org.alfresco.web.ui.common.component.UIBreadcrumb) - */ - @SuppressWarnings("unchecked") - public String navigationOutcome(UIBreadcrumb breadcrumb) - { - // set the current node to the specified top level node ID - FacesContext fc = FacesContext.getCurrentInstance(); - setCurrentNodeId(ref.getId()); - setLocation( (List)breadcrumb.getValue() ); - - // setup the dispatch context - setupDispatchContext(new Node(ref)); - - // inform any listeners that the current space has changed - UIContextService.getInstance(FacesContext.getCurrentInstance()).spaceChanged(); - - if (fc.getViewRoot().getViewId().equals(BrowseBean.BROWSE_VIEW_ID)) - { - return null; - } - else - { - return OUTCOME_BROWSE; - } - } - - public NodeRef getNodeRef() - { - return this.ref; - } - - private String label; - private NodeRef ref; - } - - - // ------------------------------------------------------------------------------ - // Private data - - private static Log s_logger = LogFactory.getLog(NavigationBean.class); - - /** constant values used by the toolbar location modelist control */ - public static final String LOCATION_COMPANY = "companyhome"; - public static final String LOCATION_HOME = "userhome"; - public static final String LOCATION_GUEST = "guesthome"; - public static final String LOCATION_MYALFRESCO = "myalfresco"; - - /** constant value representing the display lables for toolbar locations */ - public static final String MSG_MYALFRESCO = "my_alfresco"; - public static final String MSG_MYHOME = "my_home"; - public static final String MSG_COMPANYHOME = "company_home"; - public static final String MSG_GUESTHOME = "guest_home"; - - private static final String OUTCOME_MYALFRESCO = "myalfresco"; - private static final String OUTCOME_BROWSE = "browse"; - - private static final String ERROR_DELETED_FOLDER = "error_deleted_folder"; - - /** The NodeService to be used by the bean */ - transient private NodeService nodeService; - - /** The SearchService to be used by the bean */ - transient private SearchService searchService; - - /** NamespaceService bean reference */ - transient private NamespaceService namespaceService; - - /** RuleService bean reference*/ - transient private RuleService ruleService; - - /** Repo Admin Service reference */ - transient private RepoAdminService repoAdminService; - - /** File server configuration reference */ - transient private ServerConfigurationAccessor serverConfiguration; - - /** CIFS content disk driver bean reference */ - protected ContentDiskInterface contentDiskDriver; - - /** Client configuration object */ - protected ClientConfigElement clientConfig = null; - - /** The user preferences bean reference */ - UserPreferencesBean preferences; - - /** The Authentication service bean reference */ - transient private MutableAuthenticationService authService; - - /** The PermissionService reference */ - transient private PermissionService permissionService; - - /** Cached path to our CIFS server and top level node DIR */ - private String cifsServerPath; - - /** Node Id we are using for UI context operations */ - private String currentNodeId; - - /** Node we are using for UI context operations */ - private Node currentNode = null; - - /** Node we are using for dispatching */ - private Node dispatchContext = null; - - /** Node representing the guest home */ - private Node guestHomeNode = null; - - /** Node representing the company home */ - private Node companyHomeNode = null; - - /** Current toolbar location */ - private String toolbarLocation = null; - - /** Search context object we are currently using or null for no search */ - private SearchContext searchContext; - - /** expanded state of the Shelf panel wrapper component */ - private boolean shelfExpanded = true; - - /** expanded state of the Shelf item components */ - private boolean[] shelfItemExpanded = new boolean[] {true, true, true, false, false}; - - /** list of the breadcrumb handler elements representing the location path of the UI */ - private List location = null; - - /** The client Help file url */ - private String helpUrl; -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/bean/NodeEventListener.java b/war/src/main/java/org/alfresco/web/bean/NodeEventListener.java deleted file mode 100644 index 338c5a8ce4..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/NodeEventListener.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean; - -import java.io.Serializable; - -import org.alfresco.service.namespace.QName; -import org.alfresco.web.bean.repository.Node; - -/** - * @author Kevin Roast - */ -public interface NodeEventListener extends Serializable -{ - /** - * Callback executed when a Node wrapped object is created. This is generally used - * to add additional property resolvers to the Node for a specific model type. - * - * @param node The Node wrapper that has been created - * @param type Type of the Node that has been created - */ - public void created(Node node, QName type); -} diff --git a/war/src/main/java/org/alfresco/web/bean/SidebarBean.java b/war/src/main/java/org/alfresco/web/bean/SidebarBean.java deleted file mode 100644 index 147fcf81d1..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/SidebarBean.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.springframework.extensions.config.Config; -import org.alfresco.web.app.Application; -import org.alfresco.web.config.SidebarConfigElement; -import org.alfresco.web.config.SidebarConfigElement.SidebarPluginConfig; -import org.alfresco.web.ui.common.component.UIListItem; -import org.alfresco.web.ui.common.component.UIModeList; - -/** - * Managed bean used by the sidebar component to manage it's state. - * - * @author gavinc - */ -public class SidebarBean implements Serializable -{ - private static final long serialVersionUID = -2613219657864672539L; - - protected String activePlugin; - protected List plugins; - protected SidebarConfigElement sidebarConfig; - - /** - * Default constructor - */ - public SidebarBean() - { - // get the sidebar config object - this.sidebarConfig = getSidebarConfig(FacesContext.getCurrentInstance()); - - // make sure we found the config - if (this.sidebarConfig == null) - { - throw new IllegalStateException("Failed to find configuration for the sidebar"); - } - - // build the list of plugins available and check we have at least one - List items = this.getPlugins(); - if (items.size() == 0) - { - throw new IllegalStateException("Failed to find configuration for any sidebar plugins, at least one must be defined!"); - } - - // determine the default plugin - this.activePlugin = this.sidebarConfig.getDefaultPlugin(); - if (this.activePlugin == null) - { - this.activePlugin = (String)items.get(0).getValue(); - } - } - - // ------------------------------------------------------------------------------ - // Event handlers - - public void pluginChanged(ActionEvent event) - { - UIModeList pluginList = (UIModeList)event.getComponent(); - - // get the selected plugin - this.activePlugin = pluginList.getValue().toString(); - } - - // ------------------------------------------------------------------------------ - // Bean Getters and Setters - - /** - * Returns a list of configured plugins - * - * @return List of UIListItem's representing the plugins available - */ - public List getPlugins() - { - if (this.plugins == null) - { - FacesContext context = FacesContext.getCurrentInstance(); - this.plugins = new ArrayList(); - - // create a list entry for each configured plugin - for (String pluginId : this.sidebarConfig.getPlugins().keySet()) - { - SidebarPluginConfig plugin = this.sidebarConfig.getPlugin(pluginId); - - // resolve the label for the plugin - String label = plugin.getlabelId(); - if (label != null) - { - label = Application.getMessage(context, label); - } - if (label == null) - { - label = plugin.getlabel(); - } - if (label == null) - { - label = plugin.getId(); - } - - // resolve the description (tooltip for the plugin) - String tooltip = plugin.getDescriptionId(); - if (tooltip != null) - { - tooltip = Application.getMessage(context, tooltip); - } - if (tooltip == null) - { - tooltip = plugin.getDescription(); - } - - UIListItem item = new UIListItem(); - item.setValue(plugin.getId()); - item.setLabel(label); - if (tooltip != null) - { - item.setTooltip(tooltip); - } - - this.plugins.add(item); - } - } - - return this.plugins; - } - - /** - * Returns the id of the currently active plugin - * - * @return Id of the current plugin - */ - public String getActivePlugin() - { - return activePlugin; - } - - /** - * Returns the path of the JSP to use for the current plugin - * - * @return JSP to use for the current plugin - */ - public String getActivePluginPage() - { - return this.sidebarConfig.getPlugin(this.activePlugin).getPage(); - } - - // ------------------------------------------------------------------------------ - // Helper methods - - /** - * Returns the SidebarConfigElement for the application - * - * @param context Faces context - * @return The SidebarConfigElement object or null if it's not found - */ - public static SidebarConfigElement getSidebarConfig(FacesContext context) - { - SidebarConfigElement config = null; - - Config cfg = Application.getConfigService(context).getConfig("Sidebar"); - if (cfg != null) - { - config = (SidebarConfigElement)cfg.getConfigElement(SidebarConfigElement.CONFIG_ELEMENT_ID); - } - - return config; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/SpaceLinkDetailsDialog.java b/war/src/main/java/org/alfresco/web/bean/SpaceLinkDetailsDialog.java deleted file mode 100644 index c3153d33e1..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/SpaceLinkDetailsDialog.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.TemplateService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.NavigationSupport; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.NodeListUtils; -import org.alfresco.web.ui.common.NodePropertyComparator; -import org.alfresco.web.ui.common.component.UIActionLink; - -public class SpaceLinkDetailsDialog extends BaseDetailsBean implements NavigationSupport -{ - private static final long serialVersionUID = 8372741472120796169L; - - private static final String MSG_DETAILS_OF = "details_of"; - private static final String MSG_LOCATION = "location"; - private final static String MSG_CLOSE = "close"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - /** - * Returns the Space this bean is currently representing - * - * @return The Space Node - */ - public Node getSpace() - { - return getNode(); - } - - @Override - protected Node getLinkResolvedNode() - { - Node space = getSpace(); - if (ApplicationModel.TYPE_FOLDERLINK.equals(space.getType())) - { - NodeRef destRef = (NodeRef) space.getProperties().get(ContentModel.PROP_LINK_DESTINATION); - if (getNodeService().exists(destRef)) - { - space = new Node(destRef); - } - } - return space; - } - - @Override - public Node getNode() - { - return this.browseBean.getActionSpace(); - } - - @Override - protected String getPropertiesPanelId() - { - return "space-props"; - } - - @Override - public Map getTemplateModel() - { - HashMap model = new HashMap(1, 1.0f); - - model.put("space", getSpace().getNodeRef()); - model.put(TemplateService.KEY_IMAGE_RESOLVER, imageResolver); - - return model; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - public String getCurrentItemId() - { - return getId(); - } - - public void nextItem(ActionEvent event) - { - UIActionLink link = (UIActionLink) event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - NodeRef currNodeRef = new NodeRef(Repository.getStoreRef(), id); - List nodes = this.browseBean.getParentNodes(currNodeRef); - Node next = null; - if (nodes.size() > 1) - { - String currentSortColumn = this.browseBean.getSpacesRichList().getCurrentSortColumn(); - boolean currentSortDescending = this.browseBean.getSpacesRichList().isCurrentSortDescending(); - Collections.sort(nodes, new NodePropertyComparator(currentSortColumn, !currentSortDescending)); - next = NodeListUtils.nextItem(nodes, id); - this.browseBean.setupSpaceAction(next.getId(), false); - } - if (next == null) - { - Node currNode = new Node(currNodeRef); - this.navigator.setupDispatchContext(currNode); - } - } - - } - - public void previousItem(ActionEvent event) - { - UIActionLink link = (UIActionLink) event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - NodeRef currNodeRef = new NodeRef(Repository.getStoreRef(), id); - List nodes = this.browseBean.getParentNodes(currNodeRef); - Node previous = null; - if (nodes.size() > 1) - { - String currentSortColumn = this.browseBean.getSpacesRichList().getCurrentSortColumn(); - boolean currentSortDescending = this.browseBean.getSpacesRichList().isCurrentSortDescending(); - Collections.sort(nodes, new NodePropertyComparator(currentSortColumn, !currentSortDescending)); - previous = NodeListUtils.previousItem(nodes, id); - this.browseBean.setupSpaceAction(previous.getId(), false); - } - if (previous == null) - { - Node currNode = new Node(currNodeRef); - this.navigator.setupDispatchContext(currNode); - } - } - } - - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } - - @Override - public String getContainerSubTitle() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_LOCATION) + ": " + - getSpace().getNodePath().toDisplayPath(getNodeService(), getPermissionService()); - } - - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_DETAILS_OF) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) + getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - public String getOutcome() - { - return "dialog:close:dialog:showSpaceDetails"; - } - - public String cancel() - { - this.navigator.resetCurrentNodeProperties(); - return super.cancel(); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/TemplateMailHelperBean.java b/war/src/main/java/org/alfresco/web/bean/TemplateMailHelperBean.java deleted file mode 100644 index be973c439e..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/TemplateMailHelperBean.java +++ /dev/null @@ -1,317 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.mail.MessagingException; -import javax.mail.internet.MimeMessage; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.action.executer.MailActionExecuter; -import org.alfresco.repo.template.I18NMessageMethod; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.ContentReader; -import org.alfresco.service.cmr.repository.ContentService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.util.UrlUtil; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.servlet.BaseTemplateContentServlet; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.repo.component.template.DefaultModelHelper; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.mail.javamail.JavaMailSender; -import org.springframework.mail.javamail.MimeMessageHelper; -import org.springframework.mail.javamail.MimeMessagePreparator; - -/** - * @author Kevin Roast - */ -public class TemplateMailHelperBean implements Serializable -{ - private static final long serialVersionUID = 9117248002321651339L; - - private static Log logger = LogFactory.getLog(TemplateMailHelperBean.class); - - /** JavaMailSender bean reference */ - transient private JavaMailSender mailSender; - - /** NodeService bean reference */ - transient private NodeService nodeService; - - /** dialog state */ - private String subject = null; - private String body = null; - private String automaticText = null; - private String template = null; - private String usingTemplate = null; - private String finalBody; - - /** - * @param mailSender The JavaMailSender to set. - */ - public void setMailSender(JavaMailSender mailSender) - { - this.mailSender = mailSender; - } - - protected JavaMailSender getMailSender() - { - if (mailSender == null) - { - mailSender = (JavaMailSender) FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), "mailService"); - } - return mailSender; - } - - /** - * @param nodeService The nodeService to set. - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - protected NodeService getNodeService() - { - if (nodeService == null) - { - nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - } - return nodeService; - } - - /** - * Initialises the bean - */ - public TemplateMailHelperBean() - { - subject = ""; - body = ""; - automaticText = ""; - template = null; - usingTemplate = null; - } - - /** - * Send an email notification to the specified User authority - * - * @param person Person node representing the user - * @param node Node they are invited too - * @param from From text message - * @param roleText The role display label for the user invite notification - */ - public void notifyUser(NodeRef person, NodeRef node, final String from, String roleText) - { - final String to = (String)this.getNodeService().getProperty(person, ContentModel.PROP_EMAIL); - - if (to != null && to.length() != 0) - { - String body = this.body; - if (this.usingTemplate != null) - { - FacesContext fc = FacesContext.getCurrentInstance(); - - // use template service to format the email - NodeRef templateRef = new NodeRef(Repository.getStoreRef(), this.usingTemplate); - ServiceRegistry services = Repository.getServiceRegistry(fc); - Map model = DefaultModelHelper.buildDefaultModel( - services, Application.getCurrentUser(fc), templateRef); - model.put("role", roleText); - model.put("space", node); - // object to allow client urls to be generated in emails - model.put("url", new BaseTemplateContentServlet.URLHelper(fc)); - model.put("msg", new I18NMessageMethod()); - model.put("document", node); - if (nodeService.getType(node).equals(ContentModel.TYPE_CONTENT)) - { - NodeRef parentNodeRef = nodeService.getParentAssocs(node).get(0).getParentRef(); - if (parentNodeRef == null) - { - throw new IllegalArgumentException("Parent folder doesn't exists for node: " + node); - } - model.put("space", parentNodeRef); - } - model.put("shareUrl", UrlUtil.getShareUrl(services.getSysAdminParams())); - - body = services.getTemplateService().processTemplate("freemarker", templateRef.toString(), model); - } - this.finalBody = body; - - MimeMessagePreparator mailPreparer = new MimeMessagePreparator() - { - public void prepare(MimeMessage mimeMessage) throws MessagingException - { - MimeMessageHelper message = new MimeMessageHelper(mimeMessage); - message.setTo(to); - message.setSubject(subject); - message.setText(finalBody, MailActionExecuter.isHTML(finalBody)); - message.setFrom(from); - } - }; - - if (logger.isDebugEnabled()) - logger.debug("Sending notification email to: " + to + "\n...with subject:\n" + subject + "\n...with body:\n" + body); - - try - { - // Send the message - this.getMailSender().send(mailPreparer); - } - catch (Throwable e) - { - // don't stop the action but let admins know email is not getting sent - logger.error("Failed to send email to " + to, e); - } - } - } - - /** - * Action handler called to insert a template as the email body - */ - public void insertTemplate(ActionEvent event) - { - if (this.template != null && this.template.equals(TemplateSupportBean.NO_SELECTION) == false) - { - // get the content of the template so the user can get a basic preview of it - try - { - NodeRef templateRef = new NodeRef(Repository.getStoreRef(), this.template); - ContentService cs = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getContentService(); - ContentReader reader = cs.getReader(templateRef, ContentModel.PROP_CONTENT); - if (reader != null && reader.exists()) - { - this.body = reader.getContentString(); - - this.usingTemplate = this.template; - } - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err); - } - } - } - - /** - * Action handler called to discard the template from the email body - */ - public void discardTemplate(ActionEvent event) - { - this.body = this.automaticText; - usingTemplate = null; - } - - /** - * @return Returns the email body text. - */ - public String getBody() - { - return this.body; - } - - /** - * @param body The email body text to set. - */ - public void setBody(String body) - { - this.body = body; - } - - /** - * @return Returns the email subject text. - */ - public String getSubject() - { - return this.subject; - } - - /** - * @param subject The email subject text to set. - */ - public void setSubject(String subject) - { - this.subject = subject; - } - - /** - * @return Returns the automatic text. - */ - public String getAutomaticText() - { - return this.automaticText; - } - - /** - * @param automaticText The automatic text to set. - */ - public void setAutomaticText(String automaticText) - { - this.automaticText = automaticText; - } - - /** - * @return Returns the email template Id - */ - public String getTemplate() - { - return this.template; - } - - /** - * @param template The email template to set. - */ - public void setTemplate(String template) - { - this.template = template; - } - - /** - * @return Returns if a template has been inserted by a user for email body. - */ - public String getUsingTemplate() - { - return this.usingTemplate; - } - - /** - * @param usingTemplate Template that has been inserted by a user for the email body. - */ - public void setUsingTemplate(String usingTemplate) - { - this.usingTemplate = usingTemplate; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/TemplateSupportBean.java b/war/src/main/java/org/alfresco/web/bean/TemplateSupportBean.java deleted file mode 100644 index 7f7596b2d5..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/TemplateSupportBean.java +++ /dev/null @@ -1,297 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import javax.faces.context.FacesContext; -import javax.faces.model.SelectItem; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.repo.security.permissions.AccessDeniedException; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.repository.ContentData; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.search.SearchService; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.util.ExpiringValueCache; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.data.IDataContainer; -import org.alfresco.web.data.QuickSort; - -/** - * Provide access to commonly used lists of templates and script files. - *

- * The lists are cached for a small period of time to help performance in the client, - * as generally the contents of the template folders are not changed frequently. - * - * @author Kevin Roast - */ -public class TemplateSupportBean implements Serializable -{ - private static final long serialVersionUID = 6698338879903536081L; - - private static final String MSG_SELECT_TEMPLATE = "select_a_template"; - private static final String MSG_SELECT_SCRIPT = "select_a_script"; - - /** "no selection" marker for SelectItem lists */ - public static final String NO_SELECTION = "none"; - - /** NodeService instance */ - transient private NodeService nodeService; - - /** The SearchService instance */ - transient private SearchService searchService; - - /** cache of content templates that lasts 30 seconds - enough for a couple of page refreshes */ - private ExpiringValueCache> contentTemplates = new ExpiringValueCache>(1000*30); - - /** cache of email templates that lasts 30 seconds - enough for a few page refreshes */ - private ExpiringValueCache> emailTemplates = new ExpiringValueCache>(1000*30); - - /** cache of RSS templates that lasts 30 seconds - enough for a few page refreshes */ - private ExpiringValueCache> rssTemplates = new ExpiringValueCache>(1000*30); - - /** cache of JavaScript files that lasts 30 seconds - enough for a few page refreshes */ - private ExpiringValueCache> scriptFiles = new ExpiringValueCache>(1000*30); - - - /** - * @param nodeService The NodeService to set. - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - private NodeService getNodeService() - { - if (nodeService == null) - { - nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - } - return nodeService; - } - - /** - * @param searchService The SearchService to set. - */ - public void setSearchService(SearchService searchService) - { - this.searchService = searchService; - } - - private SearchService getSearchService() - { - if (searchService == null) - { - searchService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getSearchService(); - } - return searchService; - } - - /** - * @return the list of available Content Templates that can be applied to the current document. - */ - public List getContentTemplates() - { - List templates = contentTemplates.get(); - if (templates == null) - { - // get the template from the special Content Templates folder - FacesContext fc = FacesContext.getCurrentInstance(); - String xpath = Application.getRootPath(fc) + "/" + - Application.getGlossaryFolderName(fc) + "/" + - Application.getContentTemplatesFolderName(fc) + "//*"; - - templates = selectDictionaryNodes(fc, xpath, MSG_SELECT_TEMPLATE, MimetypeMap.MIMETYPE_TEXT_PLAIN); - - contentTemplates.put(templates); - } - - return templates; - } - - /** - * @return the list of available Email Templates. - */ - public List getEmailTemplates() - { - List templates = emailTemplates.get(); - if (templates == null) - { - // get the template from the special Email Templates folder - FacesContext fc = FacesContext.getCurrentInstance(); - String xpath = Application.getRootPath(fc) + "/" + - Application.getGlossaryFolderName(fc) + "/" + - Application.getEmailTemplatesFolderName(fc) + "//*"; - - templates = selectDictionaryNodes(fc, xpath, MSG_SELECT_TEMPLATE, MimetypeMap.MIMETYPE_TEXT_PLAIN); - - emailTemplates.put(templates); - } - - return templates; - } - - /** - * @return the list of available Notify Email Templates. - */ - public List getNotifyEmailTemplates() - { - List templates = null; - - // get the template from the special Email Templates folder - FacesContext fc = FacesContext.getCurrentInstance(); - String xpath = Application.getRootPath(fc) + "/" + - Application.getGlossaryFolderName(fc) + "/" + - Application.getEmailTemplatesFolderName(fc) + "/" + - Application.getNotifyEmailTemplatesFolderName(fc) + "//*"; - - templates = selectDictionaryNodes(fc, xpath, MSG_SELECT_TEMPLATE, MimetypeMap.MIMETYPE_TEXT_PLAIN); - - return templates; - } - - /** - * @return the list of available RSS Templates. - */ - public List getRSSTemplates() - { - List templates = rssTemplates.get(); - if (templates == null) - { - // get the template from the special Email Templates folder - FacesContext fc = FacesContext.getCurrentInstance(); - String xpath = Application.getRootPath(fc) + "/" + - Application.getGlossaryFolderName(fc) + "/" + - Application.getRSSTemplatesFolderName(fc) + "//*"; - - templates = selectDictionaryNodes(fc, xpath, MSG_SELECT_TEMPLATE, MimetypeMap.MIMETYPE_TEXT_PLAIN); - - rssTemplates.put(templates); - } - - return templates; - } - - /** - * @return the list of available JavaScript files that can be applied to the current document. - */ - public List getScriptFiles() - { - List scripts = this.scriptFiles.get(); - if (scripts == null) - { - // get the scripts from the special Scripts folder - FacesContext fc = FacesContext.getCurrentInstance(); - String xpath = Application.getRootPath(fc) + "/" + - Application.getGlossaryFolderName(fc) + "/" + - Application.getScriptsFolderName(fc) + "//*"; - - scripts = selectDictionaryNodes(fc, xpath, MSG_SELECT_SCRIPT, MimetypeMap.MIMETYPE_JAVASCRIPT); - - scriptFiles.put(scripts); - } - - return scripts; - } - - /** - * @param fc FacesContext - * @param xpath XPath to the nodes to select - * @param noSelectionLabel Label to add to the list if no items are found in the search - * - * @return List of SelectItem wrapper objects for the nodes found at the XPath - */ - private List selectDictionaryNodes(FacesContext fc, String xpath, String noSelectionLabel) - { - return selectDictionaryNodes(fc, xpath, noSelectionLabel, null); - } - - /** - * @param fc FacesContext - * @param xpath XPath to the nodes to select - * @param noSelectionLabel Label to add to the list if no items are found in the search - * @param mimetype Optional mimetype of items to add, will not add to list if mimetype does not match - * - * @return List of SelectItem wrapper objects for the nodes found at the XPath - */ - private List selectDictionaryNodes(FacesContext fc, String xpath, String noSelectionLabel, String mimetype) - { - List wrappers = null; - - try - { - NodeRef rootNodeRef = this.getNodeService().getRootNode(Repository.getStoreRef()); - NamespaceService resolver = Repository.getServiceRegistry(fc).getNamespaceService(); - List results = this.getSearchService().selectNodes(rootNodeRef, xpath, null, resolver, false); - - wrappers = new ArrayList(results.size() + 1); - if (results.size() != 0) - { - DictionaryService dd = Repository.getServiceRegistry(fc).getDictionaryService(); - for (NodeRef ref : results) - { - if (this.getNodeService().exists(ref) == true) - { - Node childNode = new Node(ref); - ContentData content = (ContentData)childNode.getProperties().get(ContentModel.PROP_CONTENT); - if (dd.isSubClass(childNode.getType(), ContentModel.TYPE_CONTENT) && - (mimetype == null || mimetype.equals(content.getMimetype()))) - { - wrappers.add(new SelectItem(childNode.getId(), childNode.getName())); - } - } - } - - // make sure the list is sorted by the label - QuickSort sorter = new QuickSort(wrappers, "label", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - } - } - catch (AccessDeniedException accessErr) - { - // ignore the result if we cannot access the root - } - - // add an entry (at the start) to instruct the user to select an item - if (wrappers == null) - { - wrappers = new ArrayList(1); - } - wrappers.add(0, new SelectItem(NO_SELECTION, Application.getMessage(FacesContext.getCurrentInstance(), noSelectionLabel))); - - return wrappers; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/actions/BaseActionWizard.java b/war/src/main/java/org/alfresco/web/bean/actions/BaseActionWizard.java deleted file mode 100644 index 38b1470154..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/actions/BaseActionWizard.java +++ /dev/null @@ -1,1156 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.actions; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.application.ViewHandler; -import javax.faces.component.UIViewRoot; -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.faces.model.DataModel; -import javax.faces.model.ListDataModel; -import javax.faces.model.SelectItem; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.action.ActionDefinition; -import org.alfresco.service.cmr.action.ActionService; -import org.alfresco.service.cmr.dictionary.AspectDefinition; -import org.alfresco.service.cmr.dictionary.TypeDefinition; -import org.alfresco.service.cmr.repository.ContentReader; -import org.alfresco.service.cmr.repository.ContentService; -import org.alfresco.service.cmr.repository.MimetypeService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.security.AuthorityService; -import org.alfresco.service.cmr.security.PersonService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.TemplateSupportBean; -import org.alfresco.web.bean.actions.handlers.MailHandler; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.wizard.BaseWizardBean; -import org.alfresco.web.data.IDataContainer; -import org.alfresco.web.data.QuickSort; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIGenericPicker; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.extensions.config.Config; -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigService; - -/** - * Base class for the "Run Action" and "Create Rule" wizards. - * - * @author gavinc - */ -public abstract class BaseActionWizard extends BaseWizardBean -{ - protected static final String PROP_ACTION_NAME = "actionName"; - protected static final String PROP_ACTION_SUMMARY = "actionSummary"; - protected static final String PROP_ACTION_EMAIL_RECIPIENTS= "actionEmailRecipients"; - protected static final String NO_PARAMS_MARKER = "noParamsMarker"; - protected static final String ERROR_ACTION_CANNOT_BE_EXECUTE_REPEATEDLY = "action_cannot_be_execute_repeatedly"; - - transient private ActionService actionService; - transient private MimetypeService mimetypeService; - transient private PersonService personService; - transient private AuthorityService authorityService; - - protected List actions; - protected List transformers; - protected List imageTransformers; - protected List commonAspects; - protected List removableAspects; - protected List addableAspects; - protected List testableAspects; - protected List users; - protected List encodings; - protected List objectTypes; - transient protected DataModel allActionsDataModel; - transient protected DataModel currentEmailRecipientsDataModel; - - protected boolean editingAction; - protected String action; - protected String usingTemplate = null; - protected String returnViewId = null; - - protected Map currentActionProperties; - protected List> allActionsProperties; - - protected Map actionHandlers; - - private static final Log logger = LogFactory.getLog(BaseActionWizard.class); - - // ------------------------------------------------------------------------------ - // Wizard implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - this.action = null; - this.users = null; - this.actions = null; - this.currentEmailRecipientsDataModel = null; - this.usingTemplate = null; - - this.allActionsProperties = new ArrayList>(); - this.currentActionProperties = new HashMap(3); - - this.editingAction = false; - - initialiseActionHandlers(); - } - - // ------------------------------------------------------------------------------ - // Bean Getters and Setters - - /** - * @return Returns the selected action - */ - public String getAction() - { - return this.action; - } - - /** - * @param action Sets the selected action - */ - public void setAction(String action) - { - this.action = action; - } - - /** - * @return Returns if a template has been inserted by a user for email body. - */ - public String getUsingTemplate() - { - return this.usingTemplate; - } - - /** - * @param usingTemplate Template that has been inserted by a user for the email body. - */ - public void setUsingTemplate(String usingTemplate) - { - this.usingTemplate = usingTemplate; - } - - /** - * Returns the properties for all the actions as a JSF DataModel - * - * @return JSF DataModel representing the action properties - */ - public DataModel getAllActionsDataModel() - { - if (this.allActionsDataModel == null) - { - this.allActionsDataModel = new ListDataModel(); - } - - this.allActionsDataModel.setWrappedData(this.allActionsProperties); - - return this.allActionsDataModel; - } - - /** - * Returns the properties for email recipients JSF DataModel - * - * @return JSF DataModel wrapping the current email recipients - */ - public DataModel getEmailRecipientsDataModel() - { - if (this.currentEmailRecipientsDataModel == null) - { - this.currentEmailRecipientsDataModel = new ListDataModel(); - } - - this.currentEmailRecipientsDataModel.setWrappedData(getEmailRecipients(this.currentActionProperties)); - - return this.currentEmailRecipientsDataModel; - } - - /** - * @return Gets the action settings - */ - public Map getActionProperties() - { - return this.currentActionProperties; - } - - /** - * @return Returns the list of selectable actions - */ - public List getActions() - { - if (this.actions == null) - { - List ruleActions = this.getActionService().getActionDefinitions(); - this.actions = new ArrayList(); - for (ActionDefinition ruleActionDef : ruleActions) - { - String title = ruleActionDef.getTitle(); - if (title == null || title.length() == 0) - { - title = ruleActionDef.getName(); - } - this.actions.add(new SelectItem(ruleActionDef.getName(), title)); - } - - // make sure the list is sorted by the label - QuickSort sorter = new QuickSort(this.actions, "label", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - - // add the select an action item at the start of the list - this.actions.add(0, new SelectItem("null", - Application.getMessage(FacesContext.getCurrentInstance(), "select_an_action"))); - } - - return this.actions; - } - - /** - * Returns a list of aspects that can be removed - * - * @return List of SelectItem objects representing the aspects that can be removed - */ - public List getRemovableAspects() - { - if ((this.removableAspects == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - // get the list of common aspects - this.removableAspects = new ArrayList(); - this.removableAspects.addAll(getCommonAspects()); - - // get those aspects configured to appear only in the remove aspect action - ConfigService svc = Application.getConfigService(FacesContext.getCurrentInstance()); - Config wizardCfg = svc.getConfig("Action Wizards"); - if (wizardCfg != null) - { - ConfigElement aspectsCfg = wizardCfg.getConfigElement("aspects-remove"); - if (aspectsCfg != null) - { - List aspects = readAspectsConfig(FacesContext.getCurrentInstance(), aspectsCfg); - this.removableAspects.addAll(aspects); - } - else - { - logger.warn("Could not find 'aspects-remove' configuration element"); - } - } - else - { - logger.warn("Could not find 'Action Wizards' configuration section"); - } - - // make sure the list is sorted by the label - QuickSort sorter = new QuickSort(this.removableAspects, "label", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - } - - return this.removableAspects; - } - - /** - * Returns a list of aspects that can be added - * - * @return List of SelectItem objects representing the aspects that can be added - */ - public List getAddableAspects() - { - if ((this.addableAspects == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - // get the list of common aspects - this.addableAspects = new ArrayList(); - this.addableAspects.addAll(getCommonAspects()); - - // get those aspects configured to appear only in the remove aspect action - ConfigService svc = Application.getConfigService(FacesContext.getCurrentInstance()); - Config wizardCfg = svc.getConfig("Action Wizards"); - if (wizardCfg != null) - { - ConfigElement aspectsCfg = wizardCfg.getConfigElement("aspects-add"); - if (aspectsCfg != null) - { - List aspects = readAspectsConfig(FacesContext.getCurrentInstance(), aspectsCfg); - this.addableAspects.addAll(aspects); - } - else - { - logger.warn("Could not find 'aspects-add' configuration element"); - } - } - else - { - logger.warn("Could not find 'Action Wizards' configuration section"); - } - - // make sure the list is sorted by the label - QuickSort sorter = new QuickSort(this.addableAspects, "label", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - } - - return this.addableAspects; - } - - /** - * Returns a list of aspects that can be tested i.e. hasAspect - * - * @return List of SelectItem objects representing the aspects that can be tested for - */ - public List getTestableAspects() - { - if ((this.testableAspects == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - // get the list of common aspects - this.testableAspects = new ArrayList(); - this.testableAspects.addAll(getCommonAspects()); - - // get those aspects configured to appear only in the remove aspect action - ConfigService svc = Application.getConfigService(FacesContext.getCurrentInstance()); - Config wizardCfg = svc.getConfig("Action Wizards"); - if (wizardCfg != null) - { - ConfigElement aspectsCfg = wizardCfg.getConfigElement("aspects-test"); - if (aspectsCfg != null) - { - List aspects = readAspectsConfig(FacesContext.getCurrentInstance(), aspectsCfg); - this.testableAspects.addAll(aspects); - } - else - { - logger.warn("Could not find 'aspects-test' configuration element"); - } - } - else - { - logger.warn("Could not find 'Action Wizards' configuration section"); - } - - // make sure the list is sorted by the label - QuickSort sorter = new QuickSort(this.testableAspects, "label", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - } - - return this.testableAspects; - } - - /** - * @return Returns a list of object types to allow the user to select from - */ - public List getObjectTypes() - { - if ((this.objectTypes == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - FacesContext context = FacesContext.getCurrentInstance(); - - // add the well known object type to start with - this.objectTypes = new ArrayList(5); - - // add any configured content or folder sub-types to the list - ConfigService svc = Application.getConfigService(FacesContext.getCurrentInstance()); - Config wizardCfg = svc.getConfig("Action Wizards"); - if (wizardCfg != null) - { - ConfigElement typesCfg = wizardCfg.getConfigElement("specialise-types"); - if (typesCfg != null) - { - for (ConfigElement child : typesCfg.getChildren()) - { - QName idQName = Repository.resolveToQName(child.getAttribute("name")); - TypeDefinition typeDef = this.getDictionaryService().getType(idQName); - - // make sure the type is a subtype of content or folder but not - // the content or folder type itself - if (typeDef != null && - typeDef.getName().equals(ContentModel.TYPE_CONTENT) == false && - typeDef.getName().equals(ContentModel.TYPE_FOLDER) == false && - (this.getDictionaryService().isSubClass(typeDef.getName(), ContentModel.TYPE_CONTENT) || - this.getDictionaryService().isSubClass(typeDef.getName(), ContentModel.TYPE_FOLDER))) - { - // try and get the display label from config - String label = Utils.getDisplayLabel(context, child); - - // if there wasn't a client based label try and get it from the dictionary - if (label == null) - { - label = typeDef.getTitle(this.getDictionaryService()); - } - - // finally, just use the localname - if (label == null) - { - label = idQName.getLocalName(); - } - - this.objectTypes.add(new SelectItem(idQName.toString(), label)); - } - } - - // make sure the list is sorted by the label - QuickSort sorter = new QuickSort(this.objectTypes, "label", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - - // add the select an action item at the start of the list - this.objectTypes.add(0, new SelectItem("null", - Application.getMessage(FacesContext.getCurrentInstance(), "select_a_type"))); - } - else - { - logger.warn("Could not find 'specialise-types' configuration element"); - } - } - else - { - logger.warn("Could not find 'Action Wizards' configuration section"); - } - - } - - return this.objectTypes; - } - - /** - * @return the List of users in the system wrapped in SelectItem objects - */ - public List getUsers() - { - if (this.users == null) - { - List userNodes = Repository.getUsers( - FacesContext.getCurrentInstance(), - this.getNodeService(), - this.getPersonService()); - this.users = new ArrayList(); - for (Node user : userNodes) - { - String email = (String)user.getProperties().get("email"); - if (email != null && email.length() > 0) - { - this.users.add(new SelectItem(email, (String)user.getProperties().get("fullName"))); - } - } - - // make sure the list is sorted by the label - QuickSort sorter = new QuickSort(this.users, "label", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - } - - return this.users; - } - - /** - * Returns the transformers that are available - * - * @return List of SelectItem objects representing the available transformers - */ - public List getTransformers() - { - if ((this.transformers == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - ConfigService svc = Application.getConfigService(FacesContext.getCurrentInstance()); - Config wizardCfg = svc.getConfig("Action Wizards"); - if (wizardCfg != null) - { - ConfigElement transformersCfg = wizardCfg.getConfigElement("transformers"); - if (transformersCfg != null) - { - FacesContext context = FacesContext.getCurrentInstance(); - Map mimeTypes = this.getMimetypeService().getDisplaysByMimetype(); - this.transformers = new ArrayList(); - for (ConfigElement child : transformersCfg.getChildren()) - { - String id = child.getAttribute("name"); - - // try and get the display label from config - String label = Utils.getDisplayLabel(context, child); - - // if there wasn't a client based label get it from the mime type service - if (label == null) - { - label = mimeTypes.get(id); - } - - // if there is still no label use the raw mimetype - if (label == null) - { - label = id; - } - - this.transformers.add(new SelectItem(id, label)); - } - - // make sure the list is sorted by the label - QuickSort sorter = new QuickSort(this.transformers, "label", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - } - else - { - logger.warn("Could not find 'transformers' configuration element"); - } - } - else - { - logger.warn("Could not find 'Action Wizards' configuration section"); - } - } - - return this.transformers; - } - - /** - * Returns the image transformers that are available - * - * @return List of SelectItem objects representing the available image transformers - */ - public List getImageTransformers() - { - if ((this.imageTransformers == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - ConfigService svc = Application.getConfigService(FacesContext.getCurrentInstance()); - Config wizardCfg = svc.getConfig("Action Wizards"); - if (wizardCfg != null) - { - ConfigElement transformersCfg = wizardCfg.getConfigElement("image-transformers"); - if (transformersCfg != null) - { - FacesContext context = FacesContext.getCurrentInstance(); - Map mimeTypes = this.getMimetypeService().getDisplaysByMimetype(); - this.imageTransformers = new ArrayList(); - for (ConfigElement child : transformersCfg.getChildren()) - { - String id = child.getAttribute("name"); - - // try and get the display label from config - String label = Utils.getDisplayLabel(context, child); - - // if there wasn't a client based label get it from the mime type service - if (label == null) - { - label = mimeTypes.get(id); - } - - // if there is still no label use the raw mimetype - if (label == null) - { - label = id; - } - - this.imageTransformers.add(new SelectItem(id, label)); - } - - // make sure the list is sorted by the label - QuickSort sorter = new QuickSort(this.imageTransformers, "label", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - } - else - { - logger.warn("Could not find 'image-transformers' configuration element"); - } - } - else - { - logger.warn("Could not find 'Action Wizards' configuration section"); - } - } - - return this.imageTransformers; - } - - /** - * Returns the current list of email recipients - * - * @return List of email recipients - */ - public List getEmailRecipients(Map actionProperties) - { - List currentEmailRecipients = (List) actionProperties.get(PROP_ACTION_EMAIL_RECIPIENTS); - if (currentEmailRecipients == null) - { - currentEmailRecipients = new ArrayList(4); - actionProperties.put(PROP_ACTION_EMAIL_RECIPIENTS, (Serializable)currentEmailRecipients); - } - return currentEmailRecipients; - } - - // ------------------------------------------------------------------------------ - // Action event handlers - - /** - * Displays the settings page for the current action being added - */ - public void promptForActionValues() - { - // set the flag to show we are creating a new action - this.editingAction = false; - - FacesContext context = FacesContext.getCurrentInstance(); - this.returnViewId = context.getViewRoot().getViewId(); - String viewId = null; - - HashMap actionProps = new HashMap(3); - actionProps.put(PROP_ACTION_NAME, this.action); - this.currentActionProperties = actionProps; - this.currentEmailRecipientsDataModel = null; - - // get the handler for the action, if there isn't one we presume it - // is a no-parameter action - IHandler handler = this.actionHandlers.get(this.action); - - if (handler != null && !handler.isAllowMultiple() && isActionPresent(this.action)) - { - Utils.addErrorMessage(Application.getMessage( - FacesContext.getCurrentInstance(), ERROR_ACTION_CANNOT_BE_EXECUTE_REPEATEDLY)); - return; - } - - if (handler != null) - { - // setup any UI defaults the action may have and get the location of - // the JSP used to collect the parameters - handler.setupUIDefaults(actionProps); - viewId = handler.getJSPPath(); - } - else - { - // just add the action to the list and use the title as the summary - ActionDefinition actionDef = this.getActionService().getActionDefinition(this.action); - actionProps.put(PROP_ACTION_SUMMARY, actionDef.getTitle()); - // add the no params marker so we can disable the edit action - actionProps.put(NO_PARAMS_MARKER, "no-params"); - this.allActionsProperties.add(actionProps); - - // come back to the same page we're on now as there are no params to collect - viewId = this.returnViewId; - } - - if (logger.isDebugEnabled()) - logger.debug("Added '" + this.action + "' action to list"); - - // go to the page to collect the settings - goToPage(context, viewId); - } - - /** - * Sets up the context for editing existing action values - */ - @SuppressWarnings("unchecked") - public void editAction() - { - // use the built in JSF support for retrieving the object for the - // row that was clicked by the user - int index = this.allActionsDataModel.getRowIndex(); - this.currentActionProperties = this.allActionsProperties.get(index); - this.action = (String)this.currentActionProperties.get(PROP_ACTION_NAME); - this.currentEmailRecipientsDataModel = null; - - // set the flag to show we are editing an action - this.editingAction = true; - - // remember the page we're on - FacesContext context = FacesContext.getCurrentInstance(); - this.returnViewId = context.getViewRoot().getViewId(); - - // go to the action page (as there is an edit option visible, - // there must be a handler for the action so we don't check) - goToPage(context, this.actionHandlers.get(this.action).getJSPPath()); - } - - /** - * Adds the action just setup by the user to the list of actions for the rule - */ - public void addAction() - { - FacesContext context = FacesContext.getCurrentInstance(); - - // this is called from the actions page so there must be a handler - // present so there's no need to check for null - String summary = this.actionHandlers.get(this.action).generateSummary( - context, this, this.currentActionProperties); - - if (summary != null) - { - this.currentActionProperties.put(PROP_ACTION_SUMMARY, summary); - } - - if (this.editingAction == false) - { - this.allActionsProperties.add(this.currentActionProperties); - } - - // reset the action drop down - this.action = null; - - // refresh the wizard - goToPage(context, this.returnViewId); - } - - /** - * Removes the requested action from the list - */ - public void removeAction() - { - // use the built in JSF support for retrieving the object for the - // row that was clicked by the user - @SuppressWarnings("unchecked") - int index = this.allActionsDataModel.getRowIndex(); - this.allActionsProperties.remove(index); - - // reset the action drop down - this.action = null; - - // refresh the wizard - FacesContext context = FacesContext.getCurrentInstance(); - goToPage(context, context.getViewRoot().getViewId()); - } - - /** - * Cancels the addition of the action - */ - public void cancelAddAction() - { - if (this.editingAction == false) - { - this.currentActionProperties.clear(); - } - - // reset the action drop down - this.action = null; - - // refresh the wizard - goToPage(FacesContext.getCurrentInstance(), this.returnViewId); - } - - /** - * Action handler called when the Add button is pressed to add an email recipient - */ - public void addRecipient(ActionEvent event) - { - UIGenericPicker picker = (UIGenericPicker)event.getComponent(); - String[] results = picker.getSelectedResults(); - if (results != null && results.length != 0) - { - List currentEmailRecipients = getEmailRecipients(this.currentActionProperties); - for (String authority : results) - { - // first check the authority has not already been added to the list - boolean alreadyAdded = false; - for (int i=0; i currentEmailRecipients = getEmailRecipients(this.currentActionProperties); - int index = this.currentEmailRecipientsDataModel.getRowIndex(); - currentEmailRecipients.remove(index); - } - - /** - * Action handler called to insert a template as the email body - */ - public void insertTemplate(ActionEvent event) - { - String template = (String)this.currentActionProperties.get(MailHandler.PROP_TEMPLATE); - if (template != null && template.equals(TemplateSupportBean.NO_SELECTION) == false) - { - // get the content of the template so the user can get a basic preview of it - try - { - NodeRef templateRef = new NodeRef(Repository.getStoreRef(), template); - ContentService cs = Repository.getServiceRegistry( - FacesContext.getCurrentInstance()).getContentService(); - ContentReader reader = cs.getReader(templateRef, ContentModel.PROP_CONTENT); - if (reader != null && reader.exists()) - { - this.currentActionProperties.put(MailHandler.PROP_MESSAGE, - reader.getContentString()); - - usingTemplate = template; - } - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err); - } - } - } - - /** - * Action handler called to discard the template from the email body - */ - public void discardTemplate(ActionEvent event) - { - this.currentActionProperties.put(MailHandler.PROP_MESSAGE, ""); - usingTemplate = null; - } - - - // ------------------------------------------------------------------------------ - // Service Injection - - /** - * Sets the action service - * - * @param actionService the action service - */ - public void setActionService(ActionService actionService) - { - this.actionService = actionService; - } - - protected ActionService getActionService() - { - if (actionService == null) - { - actionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getActionService(); - } - return actionService; - } - - /** - * Sets the mimetype service - * - * @param mimetypeService The mimetype service - */ - public void setMimetypeService(MimetypeService mimetypeService) - { - this.mimetypeService = mimetypeService; - } - - protected MimetypeService getMimetypeService() - { - if (mimetypeService == null) - { - mimetypeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getMimetypeService(); - } - return mimetypeService; - } - - /** - * @param personService The personService to set. - */ - public void setPersonService(PersonService personService) - { - this.personService = personService; - } - - protected PersonService getPersonService() - { - if (personService == null) - { - personService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPersonService(); - } - return personService; - } - - /** - * @param authorityService The authorityService to set. - */ - public void setAuthorityService(AuthorityService authorityService) - { - this.authorityService = authorityService; - } - - protected AuthorityService getAuthorityService() - { - if (authorityService == null) - { - authorityService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getAuthorityService(); - } - return authorityService; - } - - - // ------------------------------------------------------------------------------ - // Helper methods - - public String displayLabelForAuthority(String authority) - { - String label = authority; - - if (this.getPersonService().personExists(authority)) - { - // create the node ref, then our node representation - NodeRef ref = getPersonService().getPerson(authority); - Node node = new Node(ref); - - // setup convience function for current user full name - label = (String)node.getProperties().get(ContentModel.PROP_FIRSTNAME) + ' ' + - (String)node.getProperties().get(ContentModel.PROP_LASTNAME); - } - - return label; - } - - /** - * Navigates to the given page, used to go back and forth between the - * wizard and the actions settings pages - * - * @param context FacesContext - * @param viewId The viewId to go to - */ - protected void goToPage(FacesContext context, String viewId) - { - ViewHandler viewHandler = context.getApplication().getViewHandler(); - UIViewRoot viewRoot = viewHandler.createView(context, viewId); - viewRoot.setViewId(viewId); - context.setViewRoot(viewRoot); - context.renderResponse(); - } - - /** - * Initialises the action handlers from the current configuration. - */ - protected void initialiseActionHandlers() - { - if ((this.actionHandlers == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - ConfigService svc = Application.getConfigService(FacesContext.getCurrentInstance()); - Config wizardCfg = svc.getConfig("Action Wizards"); - if (wizardCfg != null) - { - ConfigElement actionHandlerCfg = wizardCfg.getConfigElement("action-handlers"); - if (actionHandlerCfg != null) - { - this.actionHandlers = new HashMap(20); - - // instantiate each handler and store in the map - for (ConfigElement child : actionHandlerCfg.getChildren()) - { - String actionName = child.getAttribute("name"); - String handlerClass = child.getAttribute("class"); - - if (actionName != null && actionName.length() > 0 && - handlerClass != null && handlerClass.length() > 0) - { - try - { - @SuppressWarnings("unchecked") - Class klass = Class.forName(handlerClass); - IHandler handler = (IHandler)klass.newInstance(); - this.actionHandlers.put(actionName, handler); - } - catch (Exception e) - { - throw new AlfrescoRuntimeException("Failed to setup action handler for '" + - actionName + "'", e); - } - } - } - } - else - { - logger.warn("Could not find 'action-handlers' configuration element"); - } - } - else - { - logger.warn("Could not find 'Action Wizards' configuration section"); - } - } - } - - /** - * Returns the aspects that are available in all scenarios i.e. add, remove and test - * - * @return List of SelectItem objects representing the available aspects - */ - protected List getCommonAspects() - { - if ((this.commonAspects == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - ConfigService svc = Application.getConfigService(FacesContext.getCurrentInstance()); - Config wizardCfg = svc.getConfig("Action Wizards"); - if (wizardCfg != null) - { - ConfigElement aspectsCfg = wizardCfg.getConfigElement("aspects"); - if (aspectsCfg != null) - { - this.commonAspects = readAspectsConfig(FacesContext.getCurrentInstance(), aspectsCfg); - } - else - { - logger.warn("Could not find 'aspects' configuration element"); - } - } - else - { - logger.warn("Could not find 'Action Wizards' configuration section"); - } - } - - return this.commonAspects; - } - - - protected List readAspectsConfig(FacesContext context, ConfigElement aspectsCfg) - { - List aspects = new ArrayList(); - - for (ConfigElement child : aspectsCfg.getChildren()) - { - QName idQName = Repository.resolveToQName(child.getAttribute("name")); - - if (idQName != null) - { - // try and get the display label from config - String label = Utils.getDisplayLabel(context, child); - - // if there wasn't a client based label try and get it from the dictionary - if (label == null) - { - AspectDefinition aspectDef = this.getDictionaryService().getAspect(idQName); - if (aspectDef != null) - { - label = aspectDef.getTitle(this.getDictionaryService()); - } - else - { - label = idQName.getLocalName(); - } - } - - aspects.add(new SelectItem(idQName.toString(), label)); - } - else - { - logger.warn("Failed to resolve aspect '" + child.getAttribute("name") + "'"); - } - } - - return aspects; - } - - public boolean isFinishButtonDisabled() - { - List currentEmailRecipients = (List) this.currentActionProperties.get(PROP_ACTION_EMAIL_RECIPIENTS); - if (currentEmailRecipients != null) - { - return currentEmailRecipients.isEmpty(); - } - return true; - } - - protected boolean isActionPresent(String actionName) - { - for(Map prop : allActionsProperties) - { - Serializable name = prop.get(PROP_ACTION_NAME); - if (name != null) - { - if (name.equals(actionName)) - { - return true; - } - } - } - - return false; - } - - - // ------------------------------------------------------------------------------ - // Inner classes - - /** - * Simple wrapper class for email recipient fields - */ - public static class RecipientWrapper implements Serializable - { - private static final long serialVersionUID = -3331836277440957711L; - - public RecipientWrapper(String name, String authority) - { - this.name = name; - this.authority = authority; - } - - public String getName() - { - return this.name; - } - - public String getAuthority() - { - return this.authority; - } - - public boolean equals(Object obj) - { - if (obj instanceof RecipientWrapper) - { - return this.authority.equals( ((RecipientWrapper)obj).getAuthority() ); - } - else - { - return false; - } - } - - public int hashCode() - { - return authority.hashCode(); - } - - private String name; - private String authority; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/actions/IHandler.java b/war/src/main/java/org/alfresco/web/bean/actions/IHandler.java deleted file mode 100644 index 9e507bff99..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/actions/IHandler.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.actions; - -import java.io.Serializable; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.bean.wizard.IWizardBean; - -/** - * Interface definition for a handler, classes that are responsible - * for marshalling data between the repository and the action based - * wizards. - * - * @author gavinc - */ -public interface IHandler extends Serializable -{ - /** - * Adds any properties to the given map that need default values - * before the UI is displayed to the user. - * - * @param props The current properties map - */ - public void setupUIDefaults(Map props); - - /** - * By default, a JSP with the same name as the handler will - * be loaded from a default location. If the handler has stored - * it's UI somewhere else the view id can be returned from this method. - * - * @return The path to the JSP for the handler - */ - public String getJSPPath(); - - /** - * Called at the end of the wizard. The properties relevant to - * this handler have to be placed in the repository properties - * map in the correct form for sending to the node service. - * - * @param props The current properties map - * @param repoProps The repository properties map to prepare - */ - public void prepareForSave(Map props, - Map repoProps); - - /** - * Called at the start of the edit wizard. The repository properties - * map holds the current state of this rule. Any properties relevant - * to this handler should be retrieved and setup in the current - * properties map. - * - * @param props The current properties map - * @param repoProps The properties currently in the repository - */ - public void prepareForEdit(Map props, - Map repoProps); - - /** - * Generates a summary string for this handler. The current state of - * the wizard is passed as well as the current properties map. - * - * @param context Faces context - * @param wizard The current wizard - * @param props The properties map - * @return The summary string - */ - public String generateSummary(FacesContext context, IWizardBean wizard, - Map props); - - /** - * Returns value of possibility of repeated performance of action - * - * @return true is allow multiple - */ - public boolean isAllowMultiple(); -} diff --git a/war/src/main/java/org/alfresco/web/bean/actions/RunActionWizard.java b/war/src/main/java/org/alfresco/web/bean/actions/RunActionWizard.java deleted file mode 100644 index cace0370bd..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/actions/RunActionWizard.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.actions; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.ResourceBundle; - -import javax.faces.context.FacesContext; -import javax.faces.model.SelectItem; - -import org.alfresco.repo.action.executer.CheckInActionExecuter; -import org.alfresco.service.cmr.action.Action; -import org.alfresco.service.cmr.action.ActionDefinition; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.data.IDataContainer; -import org.alfresco.web.data.QuickSort; -import org.alfresco.web.ui.common.Utils; - -/** - * Bean implementation for the "Run Action" wizard. - * - * @author gavinc - */ -public class RunActionWizard extends BaseActionWizard -{ - private static final long serialVersionUID = 975435581009378899L; - - protected boolean checkinActionPresent = false; - - // ------------------------------------------------------------------------------ - // Wizard implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - this.checkinActionPresent = false; - } - - protected String finishImpl(FacesContext context, String outcome) - throws Exception - { - // execute each action added in the wizard - for (Map actionParams : this.allActionsProperties) - { - // use the base class version of buildActionParams(), but for this we need - // to setup the currentActionProperties and action variables - String actionName = (String)actionParams.get(PROP_ACTION_NAME); - this.action = actionName; - - // remember the fact we have a checkin action - if (actionName.equals(CheckInActionExecuter.NAME)) - { - this.checkinActionPresent = true; - } - - // get the action handler to prepare for the save - Map repoActionParams = new HashMap(); - IHandler handler = this.actionHandlers.get(this.action); - if (handler != null) - { - handler.prepareForSave(actionParams, repoActionParams); - } - - // add the action to the rule - Action action = this.getActionService().createAction(actionName); - action.setParameterValues(repoActionParams); - - // execute the action on the current document node - NodeRef nodeRef = new NodeRef(Repository.getStoreRef(), this.parameters.get("id")); - this.getActionService().executeAction(action, nodeRef); - } - - return outcome; - } - - @Override - public List getActions() - { - if (this.actions == null) - { - NodeRef nodeRef = new NodeRef(Repository.getStoreRef(), this.parameters.get("id")); - List ruleActions = this.getActionService().getActionDefinitions(nodeRef); - this.actions = new ArrayList(); - for (ActionDefinition ruleActionDef : ruleActions) - { - String title = ruleActionDef.getTitle(); - if (title == null || title.length() == 0) - { - title = ruleActionDef.getName(); - } - this.actions.add(new SelectItem(ruleActionDef.getName(), title)); - } - - // make sure the list is sorted by the label - QuickSort sorter = new QuickSort(this.actions, "label", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - - // add the select an action item at the start of the list - this.actions.add(0, new SelectItem("null", - Application.getMessage(FacesContext.getCurrentInstance(), "select_an_action"))); - } - - return this.actions; - } - - @Override - protected String doPostCommitProcessing(FacesContext context, String outcome) - { - // reset the current document properties/aspects in case we have changed them - // during the execution of the custom action - Node document = this.browseBean.getDocument(); - if (document != null) - { - document.reset(); - } - - // reset the current space properties/aspects as well in case we have - // changed them during the execution of the custom action - Node space = this.browseBean.getActionSpace(); - if (space != null) - { - space.reset(); - } - - // special case handling for checkin - if it was successful the working - // copy node the Run Action Wizard was launched against will no longer - // exist, we therefore need the client to go back to the main browse view. - if (this.checkinActionPresent) - { - outcome = "browse"; - } - - return outcome; - } - - @Override - protected String getErrorMessageId() - { - return "error_actions"; - } - - /** - * @return Returns the summary data for the wizard. - */ - public String getSummary() - { - // create the summary using all the actions - StringBuilder actionsSummary = new StringBuilder(); - for (Map props : this.allActionsProperties) - { - actionsSummary.append(Utils.encode(props.get(PROP_ACTION_SUMMARY).toString())); - actionsSummary.append("
"); - } - - ResourceBundle bundle = Application.getBundle(FacesContext.getCurrentInstance()); - - return buildSummary( - new String[] {bundle.getString("actions")}, - new String[] {actionsSummary.toString()}); - } - - @Override - public boolean getNextButtonDisabled() - { - return (this.allActionsDataModel.getRowCount() == 0); - } - - @Override - public boolean getFinishButtonDisabled() - { - return (this.allActionsDataModel.getRowCount() == 0); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/actions/handlers/AddFeaturesHandler.java b/war/src/main/java/org/alfresco/web/bean/actions/handlers/AddFeaturesHandler.java deleted file mode 100644 index 101d8d2df7..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/actions/handlers/AddFeaturesHandler.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.actions.handlers; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.model.SelectItem; - -import org.alfresco.repo.action.executer.AddFeaturesActionExecuter; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.actions.BaseActionWizard; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.wizard.IWizardBean; - -/** - * Action handler implementation for the "add-features" action. - * - * @author gavinc - */ -public class AddFeaturesHandler extends BaseActionHandler -{ - private static final long serialVersionUID = -2062128886273060606L; - - protected static final String PROP_ASPECT = "aspect"; - - public String getJSPPath() - { - return getJSPPath(AddFeaturesActionExecuter.NAME); - } - - public void prepareForSave(Map actionProps, - Map repoParams) - { - QName aspect = Repository.resolveToQName((String)actionProps.get(PROP_ASPECT)); - repoParams.put(AddFeaturesActionExecuter.PARAM_ASPECT_NAME, aspect); - } - - public void prepareForEdit(Map actionProps, - Map repoParams) - { - QName aspect = (QName)repoParams.get(AddFeaturesActionExecuter.PARAM_ASPECT_NAME); - actionProps.put(PROP_ASPECT, aspect.toString()); - } - - public String generateSummary(FacesContext context, IWizardBean wizard, - Map actionProps) - { - String label = null; - String aspect = (String)actionProps.get(PROP_ASPECT); - - // find the label used by looking through the SelectItem list - for (SelectItem item : ((BaseActionWizard)wizard).getAddableAspects()) - { - if (item.getValue().equals(aspect)) - { - label = item.getLabel(); - break; - } - } - - return MessageFormat.format(Application.getMessage(context, "action_add_features"), - new Object[] {label}); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/actions/handlers/BaseActionHandler.java b/war/src/main/java/org/alfresco/web/bean/actions/handlers/BaseActionHandler.java deleted file mode 100644 index fc908af354..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/actions/handlers/BaseActionHandler.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.actions.handlers; - -import java.io.Serializable; -import java.util.Map; - -import org.alfresco.web.bean.actions.IHandler; - -/** - * Base class for all action handler implementations. - * - * @author gavinc - */ -public abstract class BaseActionHandler implements IHandler -{ - protected static final String ACTION_PAGES_LOCATION = "/jsp/actions/"; - protected static final String PROP_DESTINATION = "destinationLocation"; - - public void setupUIDefaults(Map actionProps) - { - // do nothing by default, only those action handlers that need - // to setup defaults need override this method - } - - /** - * Given the action name, generates the default path for the JSP - * - * @param actionName The name of the action - * @return The path to the JSP used for the action - */ - protected String getJSPPath(String actionName) - { - return ACTION_PAGES_LOCATION + actionName + ".jsp"; - } - - /* - * @see org.alfresco.web.bean.actions.IHandler#isAllowMultiple() - */ - public boolean isAllowMultiple() - { - return true; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/actions/handlers/CheckInHandler.java b/war/src/main/java/org/alfresco/web/bean/actions/handlers/CheckInHandler.java deleted file mode 100644 index d925d55c69..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/actions/handlers/CheckInHandler.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.actions.handlers; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.repo.action.executer.CheckInActionExecuter; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.wizard.IWizardBean; - -/** - * Action handler implementation for the "check-in" action. - * - * @author gavinc - */ -public class CheckInHandler extends BaseActionHandler -{ - private static final long serialVersionUID = 9033071326749427779L; - - protected static final String PROP_CHECKIN_DESC = "checkinDescription"; - protected static final String PROP_CHECKIN_MINOR = "checkinMinorChange"; - - @Override - public void setupUIDefaults(Map actionProps) - { - actionProps.put(PROP_CHECKIN_MINOR, Boolean.TRUE); - } - - public String getJSPPath() - { - return getJSPPath(CheckInActionExecuter.NAME); - } - - public void prepareForSave(Map actionProps, - Map repoProps) - { - repoProps.put(CheckInActionExecuter.PARAM_DESCRIPTION, - actionProps.get(PROP_CHECKIN_DESC)); - - repoProps.put(CheckInActionExecuter.PARAM_MINOR_CHANGE, - actionProps.get(PROP_CHECKIN_MINOR)); - } - - public void prepareForEdit(Map actionProps, - Map repoProps) - { - String checkDesc = (String)repoProps.get(CheckInActionExecuter.PARAM_DESCRIPTION); - actionProps.put(PROP_CHECKIN_DESC, checkDesc); - - Boolean minorChange = (Boolean)repoProps.get(CheckInActionExecuter.PARAM_MINOR_CHANGE); - actionProps.put(PROP_CHECKIN_MINOR, minorChange); - } - - public String generateSummary(FacesContext context, IWizardBean wizard, - Map actionProps) - { - String comment = (String)actionProps.get(PROP_CHECKIN_DESC); - Boolean minorChange = (Boolean)actionProps.get(PROP_CHECKIN_MINOR); - String change = null; - if (minorChange != null && minorChange.booleanValue()) - { - change = Application.getMessage(context, "minor_change"); - } - else - { - change = Application.getMessage(context, "major_change"); - } - - return MessageFormat.format(Application.getMessage(context, "action_check_in"), - new Object[] {change, comment}); - } - - /* - * @see org.alfresco.web.bean.actions.IHandler#isAllowMultiple() - */ - public boolean isAllowMultiple() - { - return false; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/actions/handlers/CheckOutHandler.java b/war/src/main/java/org/alfresco/web/bean/actions/handlers/CheckOutHandler.java deleted file mode 100644 index afbfe61e8d..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/actions/handlers/CheckOutHandler.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.actions.handlers; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.action.executer.CheckOutActionExecuter; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.wizard.IWizardBean; - -/** - * Action handler implementation for the "check-out" action. - * - * @author gavinc - */ -public class CheckOutHandler extends BaseActionHandler -{ - private static final long serialVersionUID = -7115284366068767316L; - - public String getJSPPath() - { - return getJSPPath(CheckOutActionExecuter.NAME); - } - - public void prepareForSave(Map actionProps, - Map repoProps) - { - // specify the location the checked out working copy should go - // add the destination space id to the action properties - NodeRef destNodeRef = (NodeRef)actionProps.get(PROP_DESTINATION); - repoProps.put(CheckOutActionExecuter.PARAM_DESTINATION_FOLDER, destNodeRef); - - // add the type and name of the association to create when the - // check out is performed - repoProps.put(CheckOutActionExecuter.PARAM_ASSOC_TYPE_QNAME, - ContentModel.ASSOC_CONTAINS); - repoProps.put(CheckOutActionExecuter.PARAM_ASSOC_QNAME, - QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "checkout")); - } - - public void prepareForEdit(Map actionProps, - Map repoProps) - { - NodeRef destNodeRef = (NodeRef)repoProps.get(CheckOutActionExecuter.PARAM_DESTINATION_FOLDER); - actionProps.put(PROP_DESTINATION, destNodeRef); - } - - public String generateSummary(FacesContext context, IWizardBean wizard, - Map actionProps) - { - NodeRef space = (NodeRef)actionProps.get(PROP_DESTINATION); - String spaceName = Repository.getNameForNode( - Repository.getServiceRegistry(context).getNodeService(), space); - - return MessageFormat.format(Application.getMessage(context, "action_check_out"), - new Object[] {spaceName}); - } - - /* - * @see org.alfresco.web.bean.actions.IHandler#isAllowMultiple() - */ - public boolean isAllowMultiple() - { - return false; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/actions/handlers/CopyHandler.java b/war/src/main/java/org/alfresco/web/bean/actions/handlers/CopyHandler.java deleted file mode 100644 index 48fd598e98..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/actions/handlers/CopyHandler.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.actions.handlers; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.repo.action.executer.CopyActionExecuter; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.wizard.IWizardBean; - -/** - * Action handler implementation for the "copy" action. - * - * @author gavinc - */ -public class CopyHandler extends BaseActionHandler -{ - private static final long serialVersionUID = -3570705279828902437L; - - private static final String PROP_DEEPCOPY = "deepCopy"; - - - public String getJSPPath() - { - return getJSPPath(CopyActionExecuter.NAME); - } - - public void prepareForSave(Map actionProps, - Map repoProps) - { - // add the destination space id to the action properties - NodeRef destNodeRef = (NodeRef)actionProps.get(PROP_DESTINATION); - repoProps.put(CopyActionExecuter.PARAM_DESTINATION_FOLDER, destNodeRef); - - // deep copy option - Boolean deepCopy = (Boolean)actionProps.get(PROP_DEEPCOPY); - repoProps.put(CopyActionExecuter.PARAM_DEEP_COPY, deepCopy); - } - - public void prepareForEdit(Map actionProps, - Map repoProps) - { - NodeRef destNodeRef = (NodeRef)repoProps.get(CopyActionExecuter.PARAM_DESTINATION_FOLDER); - actionProps.put(PROP_DESTINATION, destNodeRef); - - Boolean deepCopy = (Boolean)repoProps.get(CopyActionExecuter.PARAM_DEEP_COPY); - actionProps.put(PROP_DEEPCOPY, deepCopy); - } - - public String generateSummary(FacesContext context, IWizardBean wizard, - Map actionProps) - { - NodeRef space = (NodeRef)actionProps.get(PROP_DESTINATION); - String spaceName = Repository.getNameForNode( - Repository.getServiceRegistry(context).getNodeService(), space); - - return MessageFormat.format(Application.getMessage(context, "action_copy"), - new Object[] {spaceName}); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/actions/handlers/ImportHandler.java b/war/src/main/java/org/alfresco/web/bean/actions/handlers/ImportHandler.java deleted file mode 100644 index ba8439133e..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/actions/handlers/ImportHandler.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.actions.handlers; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.repo.action.executer.ImporterActionExecuter; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.wizard.IWizardBean; - -/** - * Action handler implementation for the "import" action. - * - * @author gavinc - */ -public class ImportHandler extends BaseActionHandler -{ - private static final long serialVersionUID = -3011384175544764038L; - - protected static final String IMPORT_ENCODING = "UTF-8"; - - public String getJSPPath() - { - return getJSPPath(ImporterActionExecuter.NAME); - } - - public void prepareForSave(Map actionProps, - Map repoProps) - { - // add the encoding - repoProps.put(ImporterActionExecuter.PARAM_ENCODING, IMPORT_ENCODING); - - // add the destination for the import - NodeRef destNodeRef = (NodeRef)actionProps.get(PROP_DESTINATION); - repoProps.put(ImporterActionExecuter.PARAM_DESTINATION_FOLDER, destNodeRef); - } - - public void prepareForEdit(Map actionProps, - Map repoProps) - { - NodeRef destNodeRef = (NodeRef)repoProps.get( - ImporterActionExecuter.PARAM_DESTINATION_FOLDER); - actionProps.put(PROP_DESTINATION, destNodeRef); - } - - public String generateSummary(FacesContext context, IWizardBean wizard, - Map actionProps) - { - NodeRef space = (NodeRef)actionProps.get(PROP_DESTINATION); - String spaceName = Repository.getNameForNode( - Repository.getServiceRegistry(context).getNodeService(), space); - - return MessageFormat.format(Application.getMessage(context, "action_import"), - new Object[] {spaceName}); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/actions/handlers/LinkCategoryHandler.java b/war/src/main/java/org/alfresco/web/bean/actions/handlers/LinkCategoryHandler.java deleted file mode 100644 index 18d2126c88..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/actions/handlers/LinkCategoryHandler.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.actions.handlers; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.action.executer.LinkCategoryActionExecuter; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.wizard.IWizardBean; - -/** - * Action handler implementation for the "link-category" action. - * - * @author gavinc - */ -public class LinkCategoryHandler extends BaseActionHandler -{ - private static final long serialVersionUID = -5956987738674149920L; - - protected static final String PROP_CATEGORY = "category"; - - public String getJSPPath() - { - return getJSPPath(LinkCategoryActionExecuter.NAME); - } - - public void prepareForSave(Map actionProps, - Map repoProps) - { - // add the classifiable aspect - repoProps.put(LinkCategoryActionExecuter.PARAM_CATEGORY_ASPECT, - ContentModel.ASPECT_GEN_CLASSIFIABLE); - - // put the selected category in the action params - NodeRef catNodeRef = (NodeRef)actionProps.get(PROP_CATEGORY); - repoProps.put(LinkCategoryActionExecuter.PARAM_CATEGORY_VALUE, - catNodeRef); - } - - public void prepareForEdit(Map actionProps, - Map repoProps) - { - NodeRef catNodeRef = (NodeRef)repoProps.get(LinkCategoryActionExecuter.PARAM_CATEGORY_VALUE); - actionProps.put(PROP_CATEGORY, catNodeRef); - } - - public String generateSummary(FacesContext context, IWizardBean wizard, - Map actionProps) - { - NodeRef cat = (NodeRef)actionProps.get(PROP_CATEGORY); - String name = Repository.getNameForNode( - Repository.getServiceRegistry(context).getNodeService(), cat); - - return MessageFormat.format(Application.getMessage(context, "action_link_category"), - new Object[] {name}); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/actions/handlers/MailHandler.java b/war/src/main/java/org/alfresco/web/bean/actions/handlers/MailHandler.java deleted file mode 100644 index 6900baaf32..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/actions/handlers/MailHandler.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.actions.handlers; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.repo.action.executer.MailActionExecuter; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.actions.BaseActionWizard; -import org.alfresco.web.bean.actions.BaseActionWizard.RecipientWrapper; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.wizard.IWizardBean; - -/** - * Action handler implementation for the "mail" action. - * - * @author gavinc - */ -public class MailHandler extends BaseActionHandler -{ - private static final long serialVersionUID = 622475325355334995L; - - public static final String PROP_TO = "to"; - public static final String PROP_FROM = "from"; - public static final String PROP_MESSAGE = "message"; - public static final String PROP_SUBJECT = "subject"; - public static final String PROP_TEMPLATE = "template"; - - public String getJSPPath() - { - return getJSPPath(MailActionExecuter.NAME); - } - - public void prepareForSave(Map actionProps, - Map repoProps) - { - // get hold of the current wizard so we can extract some data from it - BaseActionWizard wizard = (BaseActionWizard)Application. - getWizardManager().getBean(); - - // add the person(s) it's going to as a list of authorities - List wizardRecipients = wizard.getEmailRecipients(actionProps); - List recipients = new ArrayList(wizardRecipients.size()); - for (int i=0; i < wizardRecipients.size(); i++) - { - RecipientWrapper wrapper = wizardRecipients.get(i); - recipients.add(wrapper.getAuthority()); - } - - repoProps.put(MailActionExecuter.PARAM_TO_MANY, (Serializable)recipients); - - // add the actual email text to send - repoProps.put(MailActionExecuter.PARAM_TEXT, actionProps.get(PROP_MESSAGE)); - - // add the subject for the email - repoProps.put(MailActionExecuter.PARAM_SUBJECT, actionProps.get(PROP_SUBJECT)); - - // add the template if one was selected by the user - if (wizard.getUsingTemplate() != null) - { - repoProps.put(MailActionExecuter.PARAM_TEMPLATE, new NodeRef(Repository.getStoreRef(), - wizard.getUsingTemplate())); - } - } - - @SuppressWarnings("unchecked") -public void prepareForEdit(Map actionProps, - Map repoProps) - { - // get hold of the current wizard so we can extract some data from it - BaseActionWizard wizard = (BaseActionWizard)Application. - getWizardManager().getBean(); - - String subject = (String)repoProps.get(MailActionExecuter.PARAM_SUBJECT); - actionProps.put(PROP_SUBJECT, subject); - - String message = (String)repoProps.get(MailActionExecuter.PARAM_TEXT); - actionProps.put(PROP_MESSAGE, message); - - // handle single email or multiple authority recipients - String to = (String)repoProps.get(MailActionExecuter.PARAM_TO); - if (to != null) - { - actionProps.put(PROP_TO, to); - } - else - { - Object recipObj = repoProps.get(MailActionExecuter.PARAM_TO_MANY); - - List recipients = null; - - if ( recipObj != null) - { - if ( recipObj instanceof String) - { - recipients = new ArrayList(); - recipients.add((String) recipObj); - } - else if ( recipObj instanceof List) - { - recipients = (List) recipObj; - } - } - - if (recipients != null && recipients.size() != 0) - { - // rebuild the list of RecipientWrapper objects from the stored action - for (String authority : recipients) - { - wizard.getEmailRecipients(actionProps).add( - new RecipientWrapper(wizard.displayLabelForAuthority(authority), - authority)); - } - } - } - - NodeRef templateRef = (NodeRef)repoProps.get(MailActionExecuter.PARAM_TEMPLATE); - if (templateRef != null) - { - actionProps.put(PROP_TEMPLATE, templateRef.getId()); - wizard.setUsingTemplate(templateRef.getId()); - } - } - - public String generateSummary(FacesContext context, IWizardBean wizard, - Map actionProps) - { - BaseActionWizard actionWizard = (BaseActionWizard)wizard; - - String addresses = (String)actionProps.get(PROP_TO); - - if (addresses == null || addresses.length() == 0) - { - List wizardRecipients = actionWizard.getEmailRecipients(actionProps); - if (wizardRecipients.size() != 0) - { - StringBuilder builder = new StringBuilder(); - - for (int i=0; i < wizardRecipients.size(); i++) - { - RecipientWrapper wrapper = wizardRecipients.get(i); - if (i != 0) - { - builder.append(", "); - } - builder.append(wrapper.getName()); - } - - addresses = builder.toString(); - } - } - - return MessageFormat.format(Application.getMessage(context, "action_mail"), - new Object[] {addresses}); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/actions/handlers/MoveHandler.java b/war/src/main/java/org/alfresco/web/bean/actions/handlers/MoveHandler.java deleted file mode 100644 index eede629ff2..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/actions/handlers/MoveHandler.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.actions.handlers; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.repo.action.executer.MoveActionExecuter; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.wizard.IWizardBean; - -/** - * Action handler for the "move" action. - * - * @author gavinc - */ -public class MoveHandler extends BaseActionHandler -{ - private static final long serialVersionUID = 2778547560606246126L; - - public String getJSPPath() - { - return getJSPPath(MoveActionExecuter.NAME); - } - - public void prepareForSave(Map actionProps, - Map repoProps) - { - // add the destination space id to the action properties - NodeRef destNodeRef = (NodeRef)actionProps.get(PROP_DESTINATION); - repoProps.put(MoveActionExecuter.PARAM_DESTINATION_FOLDER, destNodeRef); - } - - public void prepareForEdit(Map actionProps, - Map repoProps) - { - NodeRef destNodeRef = (NodeRef)repoProps.get(MoveActionExecuter.PARAM_DESTINATION_FOLDER); - actionProps.put(PROP_DESTINATION, destNodeRef); - } - - public String generateSummary(FacesContext context, IWizardBean wizard, - Map actionProps) - { - NodeRef space = (NodeRef)actionProps.get(PROP_DESTINATION); - String spaceName = Repository.getNameForNode( - Repository.getServiceRegistry(context).getNodeService(), space); - - return MessageFormat.format(Application.getMessage(context, "action_move"), - new Object[] {spaceName}); - } - - /* - * @see org.alfresco.web.bean.actions.IHandler#isAllowMultiple() - */ - public boolean isAllowMultiple() - { - return false; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/actions/handlers/RemoveFeaturesHandler.java b/war/src/main/java/org/alfresco/web/bean/actions/handlers/RemoveFeaturesHandler.java deleted file mode 100644 index ee23530a30..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/actions/handlers/RemoveFeaturesHandler.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.actions.handlers; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.model.SelectItem; - -import org.alfresco.repo.action.executer.RemoveFeaturesActionExecuter; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.actions.BaseActionWizard; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.wizard.IWizardBean; - -/** - * Action handler for the "remove-features" action. - * - * @author gavinc - */ -public class RemoveFeaturesHandler extends BaseActionHandler -{ - private static final long serialVersionUID = 8725616196918341435L; - - protected static final String PROP_ASPECT = "aspect"; - - public String getJSPPath() - { - return getJSPPath(RemoveFeaturesActionExecuter.NAME); - } - - public void prepareForSave(Map actionProps, - Map repoProps) - { - QName aspect = Repository.resolveToQName((String)actionProps.get(PROP_ASPECT)); - repoProps.put(RemoveFeaturesActionExecuter.PARAM_ASPECT_NAME, aspect); - } - - public void prepareForEdit(Map actionProps, - Map repoProps) - { - QName aspect = (QName)repoProps.get(RemoveFeaturesActionExecuter.PARAM_ASPECT_NAME); - actionProps.put(PROP_ASPECT, aspect.toString()); - } - - public String generateSummary(FacesContext context, IWizardBean wizard, - Map actionProps) - { - String label = null; - String aspect = (String)actionProps.get(PROP_ASPECT); - - // find the label used by looking through the SelectItem list - for (SelectItem item : ((BaseActionWizard)wizard).getRemovableAspects()) - { - if (item.getValue().equals(aspect)) - { - label = item.getLabel(); - break; - } - } - - return MessageFormat.format(Application.getMessage(context, "action_remove_features"), - new Object[] {label}); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/actions/handlers/ScriptHandler.java b/war/src/main/java/org/alfresco/web/bean/actions/handlers/ScriptHandler.java deleted file mode 100644 index 527e393e8b..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/actions/handlers/ScriptHandler.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.actions.handlers; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.repo.action.executer.ScriptActionExecuter; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.wizard.IWizardBean; - -/** - * Action handler for the "script" action. - * - * @author gavinc - */ -public class ScriptHandler extends BaseActionHandler -{ - private static final long serialVersionUID = -8006002591602401584L; - - protected static final String PROP_SCRIPT = "script"; - - public String getJSPPath() - { - return getJSPPath(ScriptActionExecuter.NAME); - } - - public void prepareForSave(Map actionProps, - Map repoProps) - { - // add the selected script noderef to the action properties - String id = (String)actionProps.get(PROP_SCRIPT); - NodeRef scriptRef = new NodeRef(Repository.getStoreRef(), id); - repoProps.put(ScriptActionExecuter.PARAM_SCRIPTREF, scriptRef); - } - - public void prepareForEdit(Map actionProps, - Map repoProps) - { - NodeRef scriptRef = (NodeRef)repoProps.get(ScriptActionExecuter.PARAM_SCRIPTREF); - actionProps.put(PROP_SCRIPT, scriptRef.getId()); - } - - public String generateSummary(FacesContext context, IWizardBean wizard, - Map actionProps) - { - String id = (String)actionProps.get(PROP_SCRIPT); - NodeRef scriptRef = new NodeRef(Repository.getStoreRef(), id); - String scriptName = Repository.getNameForNode( - Repository.getServiceRegistry(context).getNodeService(), scriptRef); - - return MessageFormat.format(Application.getMessage(context, "action_script"), - new Object[] {scriptName}); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/actions/handlers/SimpleWorkflowHandler.java b/war/src/main/java/org/alfresco/web/bean/actions/handlers/SimpleWorkflowHandler.java deleted file mode 100644 index 71793c947c..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/actions/handlers/SimpleWorkflowHandler.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.actions.handlers; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.repo.action.executer.SimpleWorkflowActionExecuter; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.wizard.IWizardBean; - -/** - * Action handler for the "simple-workflow" action. - * - * @author gavinc - */ -public class SimpleWorkflowHandler extends BaseActionHandler -{ - private static final long serialVersionUID = 2477573776900075171L; - - public static final String PROP_APPROVE_STEP_NAME = "approveStepName"; - public static final String PROP_APPROVE_ACTION = "approveAction"; - public static final String PROP_APPROVE_FOLDER = "approveFolder"; - public static final String PROP_REJECT_STEP_PRESENT = "rejectStepPresent"; - public static final String PROP_REJECT_STEP_NAME = "rejectStepName"; - public static final String PROP_REJECT_ACTION = "rejectAction"; - public static final String PROP_REJECT_FOLDER = "rejectFolder"; - - @Override - public void setupUIDefaults(Map actionProps) - { - actionProps.put(PROP_APPROVE_ACTION, "move"); - actionProps.put(PROP_REJECT_STEP_PRESENT, "yes"); - actionProps.put(PROP_REJECT_ACTION, "move"); - } - - public String getJSPPath() - { - return getJSPPath(SimpleWorkflowActionExecuter.NAME); - } - - public void prepareForSave(Map actionProps, - Map repoProps) - { - // add the approve step name - repoProps.put(SimpleWorkflowActionExecuter.PARAM_APPROVE_STEP, - (String)actionProps.get(PROP_APPROVE_STEP_NAME)); - - // add whether the approve step will copy or move the content - boolean approveMove = true; - String approveAction = (String)actionProps.get(PROP_APPROVE_ACTION); - if (approveAction != null && approveAction.equals("copy")) - { - approveMove = false; - } - - repoProps.put(SimpleWorkflowActionExecuter.PARAM_APPROVE_MOVE, Boolean.valueOf(approveMove)); - - // add the destination folder of the content - NodeRef approveDestNodeRef = null; - Object approveDestNode = actionProps.get(PROP_APPROVE_FOLDER); - if (approveDestNode instanceof NodeRef) - { - approveDestNodeRef = (NodeRef)approveDestNode; - } - else if (approveDestNode instanceof String) - { - approveDestNodeRef = new NodeRef((String)approveDestNode); - } - repoProps.put(SimpleWorkflowActionExecuter.PARAM_APPROVE_FOLDER, approveDestNodeRef); - - // determine whether we have a reject step or not - boolean requireReject = true; - String rejectStepPresent = (String)actionProps.get(PROP_REJECT_STEP_PRESENT); - if (rejectStepPresent != null && rejectStepPresent.equals("no")) - { - requireReject = false; - } - - if (requireReject) - { - // add the reject step name - repoProps.put(SimpleWorkflowActionExecuter.PARAM_REJECT_STEP, - (String)actionProps.get(PROP_REJECT_STEP_NAME)); - - // add whether the reject step will copy or move the content - boolean rejectMove = true; - String rejectAction = (String)actionProps.get(PROP_REJECT_ACTION); - if (rejectAction != null && rejectAction.equals("copy")) - { - rejectMove = false; - } - - repoProps.put(SimpleWorkflowActionExecuter.PARAM_REJECT_MOVE, Boolean.valueOf(rejectMove)); - - // add the destination folder of the content - NodeRef rejectDestNodeRef = null; - Object rejectDestNode = actionProps.get(PROP_REJECT_FOLDER); - if (rejectDestNode instanceof NodeRef) - { - rejectDestNodeRef = (NodeRef)rejectDestNode; - } - else if (rejectDestNode instanceof String) - { - rejectDestNodeRef = new NodeRef((String)rejectDestNode); - } - repoProps.put(SimpleWorkflowActionExecuter.PARAM_REJECT_FOLDER, rejectDestNodeRef); - } - } - - public void prepareForEdit(Map actionProps, - Map repoProps) - { - String approveStep = (String)repoProps.get(SimpleWorkflowActionExecuter.PARAM_APPROVE_STEP); - Boolean approveMove = (Boolean)repoProps.get(SimpleWorkflowActionExecuter.PARAM_APPROVE_MOVE); - NodeRef approveFolderNode = (NodeRef)repoProps.get( - SimpleWorkflowActionExecuter.PARAM_APPROVE_FOLDER); - - String rejectStep = (String)repoProps.get(SimpleWorkflowActionExecuter.PARAM_REJECT_STEP); - Boolean rejectMove = (Boolean)repoProps.get(SimpleWorkflowActionExecuter.PARAM_REJECT_MOVE); - NodeRef rejectFolderNode = (NodeRef)repoProps.get( - SimpleWorkflowActionExecuter.PARAM_REJECT_FOLDER); - - actionProps.put(PROP_APPROVE_STEP_NAME, approveStep); - actionProps.put(PROP_APPROVE_ACTION, approveMove ? "move" : "copy"); - actionProps.put(PROP_APPROVE_FOLDER, approveFolderNode); - - if (rejectStep == null && rejectMove == null && rejectFolderNode == null) - { - actionProps.put(PROP_REJECT_STEP_PRESENT, "no"); - actionProps.put(PROP_REJECT_ACTION, "move"); - } - else - { - actionProps.put(PROP_REJECT_STEP_PRESENT, "yes"); - actionProps.put(PROP_REJECT_STEP_NAME, rejectStep); - actionProps.put(PROP_REJECT_ACTION, rejectMove ? "move" : "copy"); - actionProps.put(PROP_REJECT_FOLDER, rejectFolderNode); - } - } - - public String generateSummary(FacesContext context, IWizardBean wizard, - Map actionProps) - { - NodeService nodeService = Repository.getServiceRegistry(context).getNodeService(); - - String approveStepName = (String)actionProps.get(PROP_APPROVE_STEP_NAME); - String approveAction = (String)actionProps.get(PROP_APPROVE_ACTION); - NodeRef approveFolder = (NodeRef)actionProps.get(PROP_APPROVE_FOLDER); - String approveFolderName = Repository.getNameForNode(nodeService, approveFolder); - String approveMsg = MessageFormat.format( - Application.getMessage(context, "action_simple_workflow"), - new Object[] {Application.getMessage(context, approveAction), - approveFolderName, approveStepName}); - - String rejectMsg = null; - String rejectStep = (String)actionProps.get(PROP_REJECT_STEP_PRESENT); - if (rejectStep != null && "yes".equals(rejectStep)) - { - String rejectStepName = (String)actionProps.get(PROP_REJECT_STEP_NAME); - String rejectAction = (String)actionProps.get(PROP_REJECT_ACTION); - NodeRef rejectFolder = (NodeRef)actionProps.get(PROP_REJECT_FOLDER); - String rejectFolderName = Repository.getNameForNode(nodeService, rejectFolder); - rejectMsg = MessageFormat.format( - Application.getMessage(context, "action_simple_workflow"), - new Object[] {Application.getMessage(context, rejectAction), - rejectFolderName, rejectStepName}); - } - - StringBuilder builder = new StringBuilder(approveMsg); - if (rejectMsg != null) - { - builder.append(" "); - builder.append(rejectMsg); - } - - return builder.toString(); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/actions/handlers/SpecialiseTypeHandler.java b/war/src/main/java/org/alfresco/web/bean/actions/handlers/SpecialiseTypeHandler.java deleted file mode 100644 index e1d533ccd7..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/actions/handlers/SpecialiseTypeHandler.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.actions.handlers; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.model.SelectItem; - -import org.alfresco.repo.action.executer.SpecialiseTypeActionExecuter; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.actions.BaseActionWizard; -import org.alfresco.web.bean.wizard.IWizardBean; - -/** - * Action handler for the "specialise-type" action. - * - * @author gavinc - */ -public class SpecialiseTypeHandler extends BaseActionHandler -{ - private static final long serialVersionUID = 7404684895683515301L; - - public static final String PROP_OBJECT_TYPE = "objecttype"; - - public String getJSPPath() - { - return getJSPPath(SpecialiseTypeActionExecuter.NAME); - } - - public void prepareForSave(Map actionProps, - Map repoProps) - { - String objectType = (String)actionProps.get(PROP_OBJECT_TYPE); - repoProps.put(SpecialiseTypeActionExecuter.PARAM_TYPE_NAME, - QName.createQName(objectType)); - } - - public void prepareForEdit(Map actionProps, - Map repoProps) - { - QName specialiseType = (QName)repoProps.get(SpecialiseTypeActionExecuter.PARAM_TYPE_NAME); - actionProps.put(PROP_OBJECT_TYPE, specialiseType.toString()); - } - - public String generateSummary(FacesContext context, IWizardBean wizard, - Map actionProps) - { - String label = null; - String objectType = (String)actionProps.get(PROP_OBJECT_TYPE); - for (SelectItem item : ((BaseActionWizard)wizard).getObjectTypes()) - { - if (item.getValue().equals(objectType) == true) - { - label = item.getLabel(); - break; - } - } - - return MessageFormat.format(Application.getMessage(context, "action_specialise_type"), - new Object[] {label}); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/actions/handlers/TransformHandler.java b/war/src/main/java/org/alfresco/web/bean/actions/handlers/TransformHandler.java deleted file mode 100644 index 344183412d..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/actions/handlers/TransformHandler.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.actions.handlers; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.model.SelectItem; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.action.executer.TransformActionExecuter; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.actions.BaseActionWizard; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.wizard.IWizardBean; - -/** - * Action handler for the "transform" action. - * - * @author gavinc - */ -public class TransformHandler extends BaseActionHandler -{ - private static final long serialVersionUID = -1224311673192351639L; - - protected static final String PROP_TRANSFORMER = "transformer"; - - public String getJSPPath() - { - return getJSPPath(TransformActionExecuter.NAME); - } - - public void prepareForSave(Map actionProps, - Map repoProps) - { - // add the transformer to use - repoProps.put(TransformActionExecuter.PARAM_MIME_TYPE, - actionProps.get(PROP_TRANSFORMER)); - - // add the destination space id to the action properties - NodeRef destNodeRef = (NodeRef)actionProps.get(PROP_DESTINATION); - repoProps.put(TransformActionExecuter.PARAM_DESTINATION_FOLDER, destNodeRef); - - // add the type and name of the association to create when the copy - // is performed - repoProps.put(TransformActionExecuter.PARAM_ASSOC_TYPE_QNAME, - ContentModel.ASSOC_CONTAINS); - repoProps.put(TransformActionExecuter.PARAM_ASSOC_QNAME, - QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "copy")); - } - - public void prepareForEdit(Map actionProps, - Map repoProps) - { - String transformer = (String)repoProps.get(TransformActionExecuter.PARAM_MIME_TYPE); - actionProps.put(PROP_TRANSFORMER, transformer); - - NodeRef destNodeRef = (NodeRef)repoProps.get(TransformActionExecuter.PARAM_DESTINATION_FOLDER); - actionProps.put(PROP_DESTINATION, destNodeRef); - } - - public String generateSummary(FacesContext context, IWizardBean wizard, - Map actionProps) - { - String label = null; - NodeRef space = (NodeRef)actionProps.get(PROP_DESTINATION); - String name = Repository.getNameForNode( - Repository.getServiceRegistry(context).getNodeService(), space); - String transformer = (String)actionProps.get(PROP_TRANSFORMER); - - // find the label used by looking through the SelectItem list - for (SelectItem item : ((BaseActionWizard)wizard).getTransformers()) - { - if (item.getValue().equals(transformer)) - { - label = item.getLabel(); - break; - } - } - - return MessageFormat.format(Application.getMessage(context, "action_transform"), - new Object[] {name, label}); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/actions/handlers/TransformImageHandler.java b/war/src/main/java/org/alfresco/web/bean/actions/handlers/TransformImageHandler.java deleted file mode 100644 index 1738e8a2aa..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/actions/handlers/TransformImageHandler.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.actions.handlers; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.model.SelectItem; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.action.executer.ImageTransformActionExecuter; -import org.alfresco.repo.action.executer.TransformActionExecuter; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.actions.BaseActionWizard; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.wizard.IWizardBean; - -/** - * Action handler for the "transform-image" action. - * - * @author gavinc - */ -public class TransformImageHandler extends BaseActionHandler -{ - private static final long serialVersionUID = 7729555214101161605L; - - protected static final String PROP_IMAGE_TRANSFORMER = "imageTransformer"; - protected static final String PROP_TRANSFORM_OPTIONS = "transformOptions"; - - public String getJSPPath() - { - return getJSPPath(ImageTransformActionExecuter.NAME); - } - - public void prepareForSave(Map actionProps, - Map repoProps) - { - // add the transformer to use - repoProps.put(ImageTransformActionExecuter.PARAM_MIME_TYPE, - actionProps.get(PROP_IMAGE_TRANSFORMER)); - - // add the options - repoProps.put(ImageTransformActionExecuter.PARAM_CONVERT_COMMAND, - actionProps.get(PROP_TRANSFORM_OPTIONS)); - - // add the destination space id to the action properties - NodeRef destNodeRef = (NodeRef)actionProps.get(PROP_DESTINATION); - repoProps.put(ImageTransformActionExecuter.PARAM_DESTINATION_FOLDER, destNodeRef); - - // add the type and name of the association to create when the copy - // is performed - repoProps.put(TransformActionExecuter.PARAM_ASSOC_TYPE_QNAME, - ContentModel.ASSOC_CONTAINS); - repoProps.put(TransformActionExecuter.PARAM_ASSOC_QNAME, - QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "copy")); - } - - public void prepareForEdit(Map actionProps, - Map repoProps) - { - String transformer = (String)repoProps.get(TransformActionExecuter.PARAM_MIME_TYPE); - actionProps.put(PROP_IMAGE_TRANSFORMER, transformer); - - String options = (String)repoProps.get(ImageTransformActionExecuter.PARAM_CONVERT_COMMAND); - actionProps.put(PROP_TRANSFORM_OPTIONS, options != null ? options : ""); - - NodeRef destNodeRef = (NodeRef)repoProps.get(ImageTransformActionExecuter.PARAM_DESTINATION_FOLDER); - actionProps.put(PROP_DESTINATION, destNodeRef); - } - - public String generateSummary(FacesContext context, IWizardBean wizard, - Map actionProps) - { - String label = null; - NodeRef space = (NodeRef)actionProps.get(PROP_DESTINATION); - String name = Repository.getNameForNode( - Repository.getServiceRegistry(context).getNodeService(), space); - String transformer = (String)actionProps.get(PROP_IMAGE_TRANSFORMER); - String option = (String)actionProps.get(PROP_TRANSFORM_OPTIONS); - - // find the label used by looking through the SelectItem list - for (SelectItem item : ((BaseActionWizard)wizard).getImageTransformers()) - { - if (item.getValue().equals(transformer)) - { - label = item.getLabel(); - break; - } - } - - return MessageFormat.format(Application.getMessage(context, "action_transform_image"), - new Object[] {name, label, option}); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/admin/AdminConsoleDialog.java b/war/src/main/java/org/alfresco/web/bean/admin/AdminConsoleDialog.java deleted file mode 100644 index 3ccbaf664a..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/admin/AdminConsoleDialog.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.admin; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; - -public class AdminConsoleDialog extends BaseDialogBean -{ - private static final long serialVersionUID = -2520599525975495006L; - - private static final String BUTTON_CLOSE = "close"; - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return outcome; - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), BUTTON_CLOSE); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/admin/AdminNodeBrowseBean.java b/war/src/main/java/org/alfresco/web/bean/admin/AdminNodeBrowseBean.java deleted file mode 100644 index a47e30e13d..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/admin/AdminNodeBrowseBean.java +++ /dev/null @@ -1,1063 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.admin; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import javax.faces.application.FacesMessage; -import javax.faces.context.FacesContext; -import javax.faces.model.DataModel; -import javax.faces.model.ListDataModel; -import javax.faces.model.SelectItem; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.service.cmr.dictionary.DataTypeDefinition; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.cmr.repository.AssociationRef; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.repository.Path; -import org.alfresco.service.cmr.repository.StoreRef; -import org.alfresco.service.cmr.search.ResultSet; -import org.alfresco.service.cmr.search.SearchService; -import org.alfresco.service.cmr.security.AccessPermission; -import org.alfresco.service.cmr.security.AccessStatus; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.service.namespace.RegexQNamePattern; -import org.alfresco.service.transaction.TransactionService; -import org.alfresco.util.ISO9075; -import org.alfresco.web.app.servlet.DownloadContentServlet; -import org.alfresco.web.bean.repository.Repository; - -// TODO: DownloadServlet - use of request parameter for property name? -// TODO: Anyway to switch content view url link / property value text? - -/** - * Backing bean to support the Admin Node Browser - */ -public class AdminNodeBrowseBean implements Serializable -{ - private static final long serialVersionUID = -8702324672426537379L; - - /** selected query language */ - private String queryLanguage = null; - - /** available query languages */ - private static List queryLanguages = new ArrayList(); - static - { - queryLanguages.add(new SelectItem("noderef")); - queryLanguages.add(new SelectItem(SearchService.LANGUAGE_XPATH)); - queryLanguages.add(new SelectItem(SearchService.LANGUAGE_LUCENE)); - queryLanguages.add(new SelectItem(SearchService.LANGUAGE_FTS_ALFRESCO)); - queryLanguages.add(new SelectItem(SearchService.LANGUAGE_CMIS_STRICT)); - queryLanguages.add(new SelectItem(SearchService.LANGUAGE_CMIS_ALFRESCO)); - queryLanguages.add(new SelectItem(SearchService.LANGUAGE_SOLR_FTS_ALFRESCO)); - queryLanguages.add(new SelectItem(SearchService.LANGUAGE_SOLR_CMIS)); - queryLanguages.add(new SelectItem("selectnodes")); - } - - // query and results - private String query = null; - private SearchResults searchResults = new SearchResults((List) null); - - private NodeRef nodeRef = null; - private QName nodeType = null; - private Path primaryPath = null; - private Boolean inheritPermissions = null; - private Long searchElapsedTime = null; - - // stores and node - transient private DataModel stores = null; - transient private DataModel parents = null; - transient private DataModel aspects = null; - transient private DataModel properties = null; - transient private DataModel children = null; - transient private DataModel assocs = null; - transient private DataModel sourceAssocs = null; - transient private DataModel permissions = null; - transient private DataModel permissionMasks = null; - - // supporting repository services - transient private TransactionService transactionService; - transient private NodeService nodeService; - transient private DictionaryService dictionaryService; - transient private SearchService searchService; - transient private NamespaceService namespaceService; - transient private PermissionService permissionService; - - /** - * @param transactionService transaction service - */ - public void setTransactionService(TransactionService transactionService) - { - this.transactionService = transactionService; - } - - private TransactionService getTransactionService() - { - if (transactionService == null) - { - transactionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getTransactionService(); - } - return transactionService; - } - - /** - * @param nodeService node service - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - private NodeService getNodeService() - { - if (nodeService == null) - { - nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - } - return nodeService; - } - - /** - * @param searchService search service - */ - public void setSearchService(SearchService searchService) - { - this.searchService = searchService; - } - - private SearchService getSearchService() - { - if (searchService == null) - { - searchService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getSearchService(); - } - return searchService; - } - - /** - * @param dictionaryService dictionary service - */ - public void setDictionaryService(DictionaryService dictionaryService) - { - this.dictionaryService = dictionaryService; - } - - private DictionaryService getDictionaryService() - { - if (dictionaryService == null) - { - dictionaryService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getDictionaryService(); - } - return dictionaryService; - } - - /** - * @param namespaceService namespace service - */ - public void setNamespaceService(NamespaceService namespaceService) - { - this.namespaceService = namespaceService; - } - - private NamespaceService getNamespaceService() - { - if (namespaceService == null) - { - namespaceService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNamespaceService(); - } - return namespaceService; - } - - /** - * @param permissionService permission service - */ - public void setPermissionService(PermissionService permissionService) - { - this.permissionService = permissionService; - } - - private PermissionService getPermissionService() - { - if (permissionService == null) - { - permissionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPermissionService(); - } - return permissionService; - } - - /** - * Gets the list of repository stores - * - * @return stores - */ - public DataModel getStores() - { - if (stores == null) - { - List storeRefs = getNodeService().getStores(); - stores = new ListDataModel(storeRefs); - } - return stores; - } - - /** - * Gets the selected node reference - * - * @return node reference (defaults to system store root) - */ - public NodeRef getNodeRef() - { - if (nodeRef == null) - { - nodeRef = getNodeService().getRootNode(new StoreRef("system", "system")); - } - return nodeRef; - } - - /** - * Sets the selected node reference - * - * @param nodeRef node reference - */ - private void setNodeRef(NodeRef nodeRef) - { - this.nodeRef = nodeRef; - - // clear cache - primaryPath = null; - nodeType = null; - parents = null; - aspects = null; - properties = null; - children = null; - assocs = null; - sourceAssocs = null; - inheritPermissions = null; - permissions = null; - permissionMasks = null; - } - - /** - * Gets the current node type - * - * @return node type - */ - public QName getNodeType() - { - if (nodeType == null) - { - nodeType = getNodeService().getType(getNodeRef()); - } - return nodeType; - } - - /** - * Gets the current node primary path - * - * @return primary path - */ - public String getPrimaryPath() - { - if (primaryPath == null) - { - primaryPath = getNodeService().getPath(getNodeRef()); - } - return ISO9075.decode(primaryPath.toString()); - } - - /** - * Gets the current node primary parent reference - * - * @return primary parent ref - */ - public NodeRef getPrimaryParent() - { - getPrimaryPath(); - Path.Element element = primaryPath.last(); - NodeRef parentRef = ((Path.ChildAssocElement) element).getRef().getParentRef(); - return parentRef; - } - - /** - * Gets the current node aspects - * - * @return node aspects - */ - public DataModel getAspects() - { - if (aspects == null) - { - List aspectNames = new ArrayList(getNodeService().getAspects(getNodeRef())); - aspects = new ListDataModel(aspectNames); - } - return aspects; - } - - /** - * Gets the current node parents - * - * @return node parents - */ - public DataModel getParents() - { - if (parents == null) - { - List parentRefs = getNodeService().getParentAssocs(getNodeRef()); - parents = new ListDataModel(parentRefs); - } - return parents; - } - - /** - * Gets the current node properties - * - * @return properties - */ - public DataModel getProperties() - { - if (properties == null) - { - Map propertyValues = getNodeService().getProperties(getNodeRef()); - List nodeProperties = new ArrayList(propertyValues.size()); - for (Map.Entry property : propertyValues.entrySet()) - { - nodeProperties.add(new Property(property.getKey(), property.getValue())); - } - properties = new ListDataModel(nodeProperties); - } - return properties; - } - - /** - * Gets whether the current node inherits its permissions from a parent node - * - * @return true => inherits permissions - */ - public boolean getInheritPermissions() - { - if (inheritPermissions == null) - { - inheritPermissions = this.getPermissionService().getInheritParentPermissions(nodeRef); - } - return inheritPermissions.booleanValue(); - } - - /** - * Gets the current node permissions - * - * @return the permissions - */ - public DataModel getPermissions() - { - if (permissions == null) - { - AccessStatus readPermissions = this.getPermissionService().hasPermission(nodeRef, PermissionService.READ_PERMISSIONS); - if (readPermissions.equals(AccessStatus.ALLOWED)) - { - List nodePermissions = new ArrayList(getPermissionService().getAllSetPermissions(nodeRef)); - permissions = new ListDataModel(nodePermissions); - } - else - { - List noReadPermissions = new ArrayList(1); - noReadPermissions.add(new NoReadPermissionGranted()); - permissions = new ListDataModel(noReadPermissions); - } - } - return permissions; - } - - /** - * Gets the current node permissions - * - * @return the permissions - */ - public DataModel getStorePermissionMasks() - { - if (permissionMasks == null) - { - List noReadPermissions = new ArrayList(1); - noReadPermissions.add(new NoStoreMask()); - permissionMasks = new ListDataModel(noReadPermissions); - } - return permissionMasks; - } - - /** - * Gets the current node children - * - * @return node children - */ - public DataModel getChildren() - { - if (children == null) - { - List assocRefs = getNodeService().getChildAssocs(getNodeRef()); - children = new ListDataModel(assocRefs); - } - return children; - } - - /** - * Gets the current node associations - * - * @return associations - */ - public DataModel getAssocs() - { - if (assocs == null) - { - try - { - List assocRefs = getNodeService().getTargetAssocs(getNodeRef(), RegexQNamePattern.MATCH_ALL); - assocs = new ListDataModel(assocRefs); - } - catch (UnsupportedOperationException err) - { - // some stores do not support associations - } - } - return assocs; - } - - /** - * Gets the current source associations - * - * @return associations - */ - public DataModel getSourceAssocs() - { - if (sourceAssocs == null) - { - try - { - List assocRefs = getNodeService().getSourceAssocs(getNodeRef(), RegexQNamePattern.MATCH_ALL); - sourceAssocs = new ListDataModel(assocRefs); - } - catch (UnsupportedOperationException err) - { - // some stores do not support associations - } - } - return sourceAssocs; - } - - /** - * Gets the current query language - * - * @return query language - */ - public String getQueryLanguage() - { - return queryLanguage; - } - - /** - * Sets the current query language - * - * @param queryLanguage query language - */ - public void setQueryLanguage(String queryLanguage) - { - this.queryLanguage = queryLanguage; - } - - /** - * Gets the current query - * - * @return query statement - */ - public String getQuery() - { - return query; - } - - /** - * Set the current query - * - * @param query query statement - */ - public void setQuery(String query) - { - this.query = query; - } - - /** - * Gets the list of available query languages - * - * @return query languages - */ - public List getQueryLanguages() - { - return queryLanguages; - } - - /** - * Gets the current search results - * - * @return search results - */ - public SearchResults getSearchResults() - { - return searchResults; - } - - /** - * Action to select a store - * - * @return next action - */ - public String selectStore() - { - StoreRef storeRef = (StoreRef) getStores().getRowData(); - NodeRef rootNode = getNodeService().getRootNode(storeRef); - setNodeRef(rootNode); - - return "success"; - } - - /** - * Action to select stores list - * - * @return next action - */ - public String selectStores() - { - stores = null; - return "success"; - } - - /** - * Action to select primary path - * - * @return next action - */ - public String selectPrimaryPath() - { - // force refresh of self - setNodeRef(nodeRef); - return "success"; - } - - /** - * Action to select primary parent - * - * @return next action - */ - public String selectPrimaryParent() - { - setNodeRef(getPrimaryParent()); - return "success"; - } - - /** - * Action to select parent - * - * @return next action - */ - public String selectParent() - { - ChildAssociationRef assocRef = (ChildAssociationRef) getParents().getRowData(); - NodeRef parentRef = assocRef.getParentRef(); - setNodeRef(parentRef); - return "success"; - } - - /** - * Action to select association To node - * - * @return next action - */ - public String selectToNode() - { - AssociationRef assocRef = (AssociationRef) getAssocs().getRowData(); - NodeRef targetRef = assocRef.getTargetRef(); - setNodeRef(targetRef); - return "success"; - } - - /** - * Action to select association From node - * - * @return next action - */ - public String selectFromNode() - { - AssociationRef assocRef = (AssociationRef) getSourceAssocs().getRowData(); - NodeRef sourceRef = assocRef.getSourceRef(); - setNodeRef(sourceRef); - return "success"; - } - - /** - * Action to select node property - * - * @return next action - */ - public String selectNodeProperty() - { - Property property = (Property) getProperties().getRowData(); - Property.Value value = (Property.Value) property.getValues().getRowData(); - NodeRef nodeRef = (NodeRef) value.getValue(); - setNodeRef(nodeRef); - return "success"; - } - - /** - * Action to select child - * - * @return next action - */ - public String selectChild() - { - ChildAssociationRef assocRef = (ChildAssociationRef) getChildren().getRowData(); - NodeRef childRef = assocRef.getChildRef(); - setNodeRef(childRef); - return "success"; - } - - /** - * Action to select search result node - * - * @return next action - */ - public String selectResultNode() - { - ChildAssociationRef assocRef = (ChildAssociationRef) searchResults.getRows().getRowData(); - NodeRef childRef = assocRef.getChildRef(); - setNodeRef(childRef); - return "success"; - } - - /** - * Action to submit search - * - * @return next action - */ - public String submitSearch() - { - long start = System.currentTimeMillis(); - RetryingTransactionCallback searchCallback = new RetryingTransactionCallback() - { - public String execute() throws Throwable - { - if (queryLanguage.equals("noderef")) - { - // ensure node exists - NodeRef nodeRef = new NodeRef(query); - boolean exists = getNodeService().exists(nodeRef); - if (!exists) - { - throw new AlfrescoRuntimeException("Node " + nodeRef + " does not exist."); - } - setNodeRef(nodeRef); - return "node"; - } - else if (queryLanguage.equals("selectnodes")) - { - List nodes = getSearchService().selectNodes(getNodeRef(), query, null, getNamespaceService(), false); - searchResults = new SearchResults(nodes); - return "search"; - } - - // perform search - searchResults = new SearchResults(getSearchService().query(getNodeRef().getStoreRef(), queryLanguage, query)); - return "search"; - } - }; - - try - { - String result = getTransactionService().getRetryingTransactionHelper().doInTransaction(searchCallback, true); - this.searchElapsedTime = System.currentTimeMillis() - start; - return result; - } - catch (Throwable e) - { - FacesContext context = FacesContext.getCurrentInstance(); - FacesMessage message = new FacesMessage(); - message.setSeverity(FacesMessage.SEVERITY_ERROR); - message.setDetail("Search failed due to: " + e.toString()); - context.addMessage("searchForm:query", message); - return "error"; - } - } - - /** - * @return the searchElapsedTime - */ - public Long getSearchElapsedTime() - { - return this.searchElapsedTime; - } - - /** - * Property wrapper class - */ - public class Property - { - private QName name; - - private boolean isCollection = false; - - private DataModel values; - - private String datatype; - - private String residual; - - /** - * Construct - * - * @param name property name - * @param value property values - */ - @SuppressWarnings("unchecked") - public Property(QName name, Serializable value) - { - this.name = name; - - PropertyDefinition propDef = getDictionaryService().getProperty(name); - if (propDef != null) - { - datatype = propDef.getDataType().getName().toString(); - residual = "false"; - } - else - { - residual = "true"; - } - - // handle multi/single values - final List values; - if (value instanceof Collection) - { - Collection oldValues = (Collection) value; - values = new ArrayList(oldValues.size()); - isCollection = true; - for (Serializable multiValue : oldValues) - { - values.add(new Value(multiValue)); - } - } - else - { - values = Collections.singletonList(new Value(value)); - } - this.values = new ListDataModel(values); - } - - /** - * Gets the property name - * - * @return name - */ - public QName getName() - { - return name; - } - - /** - * Gets the property data type - * - * @return data type - */ - public String getDataType() - { - return datatype; - } - - /** - * Gets the property value - * - * @return value - */ - public DataModel getValues() - { - return values; - } - - /** - * Determines whether the property is residual - * - * @return true => property is not defined in dictionary - */ - public String getResidual() - { - return residual; - } - - /** - * Determines whether the property is of ANY type - * - * @return true => is any - */ - public boolean isAny() - { - return (datatype == null) ? false : datatype.equals(DataTypeDefinition.ANY.toString()); - } - - /** - * Determines whether the property is a collection - * - * @return true => is collection - */ - public boolean isCollection() - { - return isCollection; - } - - /** - * Value wrapper - */ - public class Value - { - private Serializable value; - - /** - * Construct - * - * @param value value - */ - public Value(Serializable value) - { - this.value = value; - } - - /** - * Gets the value - * - * @return the value - */ - public Serializable getValue() - { - return value; - } - - /** - * Gets the value datatype - * - * @return the value datatype - */ - public String getDataType() - { - String datatype = Property.this.getDataType(); - if (datatype == null || datatype.equals(DataTypeDefinition.ANY.toString())) - { - if (value != null) - { - DataTypeDefinition dataTypeDefinition = getDictionaryService().getDataType(value.getClass()); - if (dataTypeDefinition != null) - { - datatype = getDictionaryService().getDataType(value.getClass()).getName().toString(); - } - } - } - return datatype; - } - - /** - * Gets the download url (for content properties) - * - * @return url - */ - public String getUrl() - { - String url = FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath(); - url += DownloadContentServlet.generateBrowserURL(nodeRef, "file.bin"); - url += "?property=" + name; - return url; - } - - /** - * Determines whether the value is content - * - * @return true => is content - */ - public boolean isContent() - { - String datatype = getDataType(); - return (datatype == null) ? false : datatype.equals(DataTypeDefinition.CONTENT.toString()); - } - - /** - * Determines whether the value is a node ref - * - * @return true => is node ref - */ - public boolean isNodeRef() - { - String datatype = getDataType(); - return (datatype == null) ? false : datatype.equals(DataTypeDefinition.NODE_REF.toString()) || datatype.equals(DataTypeDefinition.CATEGORY.toString()); - } - - /** - * Determines whether the value is null - * - * @return true => value is null - */ - public boolean isNullValue() - { - return value == null; - } - } - } - - /** - * Permission representing the fact that "Read Permissions" has not been granted - */ - public static class NoReadPermissionGranted implements Serializable - { - private static final long serialVersionUID = -6256369557521402921L; - - public String getPermission() - { - return PermissionService.READ_PERMISSIONS; - } - - public String getAuthority() - { - return "[Current Authority]"; - } - - public String getAccessStatus() - { - return "Not Granted"; - } - } - - public static class NoStoreMask implements Serializable - { - private static final long serialVersionUID = -6256369557521402921L; - - public String getPermission() - { - return "All "; - } - - public String getAuthority() - { - return "All"; - } - - public String getAccessStatus() - { - return "Allowed"; - } - } - - /** - * Wrapper class for Search Results - */ - public class SearchResults implements Serializable - { - private static final long serialVersionUID = 7402906720039176001L; - - private int length = 0; - private SerialListDataModel rows; - - /** - * Construct - * - * @param resultSet query result set - */ - public SearchResults(ResultSet resultSet) - { - rows = new SerialListDataModel(); - if (resultSet != null) - { - try - { - rows.setWrappedData(resultSet.getChildAssocRefs()); - length = resultSet.length(); - } - finally - { - resultSet.close(); - } - } - } - - /** - * Construct - * - * @param resultSet query result set - */ - public SearchResults(List resultSet) - { - rows = new SerialListDataModel(); - if (resultSet != null) - { - List assocRefs = new ArrayList(resultSet.size()); - for (NodeRef nodeRef : resultSet) - { - ChildAssociationRef childAssocRef = getNodeService().getPrimaryParent(nodeRef); - assocRefs.add(childAssocRef); - } - rows.setWrappedData(assocRefs); - length = resultSet.size(); - } - } - - /** - * Gets the row count - * - * @return count of rows - */ - public int getLength() - { - return length; - } - - /** - * Gets the rows - * - * @return the rows - */ - public DataModel getRows() - { - return rows; - } - - private class SerialListDataModel extends ListDataModel implements Serializable - { - private static final long serialVersionUID = 4154583769762846020L; - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/admin/ConfigAdminConsoleBean.java b/war/src/main/java/org/alfresco/web/bean/admin/ConfigAdminConsoleBean.java deleted file mode 100644 index 70d2683ccf..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/admin/ConfigAdminConsoleBean.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.admin; - -import java.io.PrintWriter; -import java.io.StringWriter; - -import org.alfresco.web.config.ConfigAdminInterpreter; - - -/** - * Backing bean to support the Web Client Config Admin Console - */ -public class ConfigAdminConsoleBean -{ - // command - private String command = ""; - private String submittedCommand = "none"; - private long duration = 0L; - private String result = null; - - // supporting repository services - private ConfigAdminInterpreter configAdminInterpreter; - - - /** - * @param configAdminInterpreter Web Client config admin interpreter - */ - public void setConfigAdminInterpreter(ConfigAdminInterpreter configAdminInterpreter) - { - this.configAdminInterpreter = configAdminInterpreter; - } - - /** - * Gets the command result - * - * @return result - */ - public String getResult() - { - if (result == null) - { - interpretCommand("help"); - } - return result; - } - - /** - * Sets the command result - * - * @param result String - */ - public void setResult(String result) - { - this.result = result; - } - - /** - * Gets the current query - * - * @return query statement - */ - public String getCommand() - { - return command; - } - - /** - * Set the current command - * - * @param command command - */ - public void setCommand(String command) - { - this.command = command; - } - - /** - * Gets the submitted command - * - * @return submitted command - */ - public String getSubmittedCommand() - { - return submittedCommand; - } - - /** - * Set the submitted command - * - * @param submittedCommand The submitted command - */ - public void setSubmittedCommand(String submittedCommand) - { - this.submittedCommand = submittedCommand; - } - - /** - * Gets the last command duration - * - * @return command duration - */ - public long getDuration() - { - return duration; - } - - /** - * Set the duration - * - * @param duration The duration - */ - public void setDuration(long duration) - { - this.duration = duration; - } - - /** - * Action to submit command - * - * @return next action - */ - public String submitCommand() - { - interpretCommand(command); - return "success"; - } - - /** - * Gets the current user name - * - * @return user name - */ - public String getCurrentUserName() - { - return configAdminInterpreter.getCurrentUserName(); - } - - /** - * Interpret repo admin console command - * - * @param command command - */ - private void interpretCommand(String command) - { - try - { - long startms = System.currentTimeMillis(); - String result = configAdminInterpreter.interpretCommand(command); - setDuration(System.currentTimeMillis() - startms); - setResult(result); - setCommand(""); - setSubmittedCommand(command); - } - catch (Exception e) - { - StringWriter stackTrace = new StringWriter(); - e.printStackTrace(new PrintWriter(stackTrace)); - setResult(stackTrace.toString()); - } - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/admin/ExportDialog.java b/war/src/main/java/org/alfresco/web/bean/admin/ExportDialog.java deleted file mode 100644 index 512fef2bd8..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/admin/ExportDialog.java +++ /dev/null @@ -1,324 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.admin; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.HashMap; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.repo.action.executer.ExporterActionExecuter; -import org.alfresco.repo.action.executer.RepositoryExporterActionExecuter; -import org.alfresco.service.cmr.action.Action; -import org.alfresco.service.cmr.action.ActionService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.BrowseBean; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Repository; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Backing bean implementation for the Export dialog. - * - * @author gavinc - */ -public class ExportDialog extends BaseDialogBean -{ - private static final long serialVersionUID = -2592252768301728700L; - - private static final Log logger = LogFactory.getLog(ExportDialog.class); - - private static final String ALL_SPACES = "all"; - private static final String CURRENT_SPACE = "current"; - private static final String DEFAULT_OUTCOME = "dialog:close"; - private static final String MSG_EXPORT_TITLE = "export_title"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - protected BrowseBean browseBean; - transient private ActionService actionService; - - private String packageName; - private String encoding = "UTF-8"; - private String mode = CURRENT_SPACE; - private NodeRef destination; - private boolean includeChildren = true; - private boolean runInBackground = true; - private boolean includeSelf; - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - if (logger.isDebugEnabled()) - logger.debug("Called export for " + this.mode + " with package name: " + this.packageName); - - // construct appropriate action to execute - Action action = null; - NodeRef startNode = this.browseBean.getActionSpace().getNodeRef(); - - // get the appropriate node - if (this.mode.equals(ALL_SPACES)) - { - Map params = new HashMap(5); - params.put(ExporterActionExecuter.PARAM_PACKAGE_NAME, this.packageName); - params.put(ExporterActionExecuter.PARAM_DESTINATION_FOLDER, this.destination); - action = this.getActionService().createAction(RepositoryExporterActionExecuter.NAME, params); - } - else - { - Map params = new HashMap(5); - params.put(ExporterActionExecuter.PARAM_STORE, Repository.getStoreRef().toString()); - params.put(ExporterActionExecuter.PARAM_PACKAGE_NAME, this.packageName); - params.put(ExporterActionExecuter.PARAM_ENCODING, this.encoding); - params.put(ExporterActionExecuter.PARAM_DESTINATION_FOLDER, this.destination); - params.put(ExporterActionExecuter.PARAM_INCLUDE_CHILDREN, Boolean.valueOf(includeChildren)); - params.put(ExporterActionExecuter.PARAM_INCLUDE_SELF, new Boolean(includeSelf)); - action = this.getActionService().createAction(ExporterActionExecuter.NAME, params); - } - - // execute action - action.setExecuteAsynchronously(this.runInBackground); - this.getActionService().executeAction(action, startNode); - - if (logger.isDebugEnabled()) - { - logger.debug("Executed space export action with action params of " + action.getParameterValues()); - } - - // reset the bean - reset(); - - return outcome; - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - String name = Application.getMessage(fc, MSG_LEFT_QUOTE) - + browseBean.getActionSpace().getName() - + Application.getMessage(fc, MSG_RIGHT_QUOTE); - return MessageFormat.format(Application.getMessage(fc, MSG_EXPORT_TITLE), name); - } - - /** - * Action called when the dialog is cancelled, just resets the bean's state - * - * @return The outcome - */ - public String cancel() - { - reset(); - - return DEFAULT_OUTCOME; - } - - /** - * Resets the dialog state back to the default - */ - public void reset() - { - this.packageName = null; - this.mode = CURRENT_SPACE; - this.destination = null; - this.includeChildren = true; - this.includeSelf = false; - this.runInBackground = true; - } - - /** - * Returns the package name for the export - * - * @return The export package name - */ - public String getPackageName() - { - return this.packageName; - } - - /** - * Sets the package name for the export - * - * @param packageName The export package name - */ - public void setPackageName(String packageName) - { - this.packageName = packageName; - } - - /** - * The destination for the export as a NodeRef - * - * @return The destination - */ - public NodeRef getDestination() - { - return this.destination; - } - - /** - * Sets the destination for the export - * - * @param destination The destination for the export - */ - public void setDestination(NodeRef destination) - { - this.destination = destination; - } - - /** - * Determines whether the export will include child spaces - * - * @return true includes children - */ - public boolean getIncludeChildren() - { - return this.includeChildren; - } - - /** - * Sets whether child spaces are included in the export - * - * @param includeChildren true to include the child spaces - */ - public void setIncludeChildren(boolean includeChildren) - { - this.includeChildren = includeChildren; - } - - /** - * Determines whether the export will include the space itself - * - * @return true includes the space being exported from - */ - public boolean getIncludeSelf() - { - return this.includeSelf; - } - - /** - * Sets whether the space itself is included in the export - * - * @param includeSelf true to include the space itself - */ - public void setIncludeSelf(boolean includeSelf) - { - this.includeSelf = includeSelf; - } - - /** - * Determines whether to export only the current space or all spaces - * - * @return "all" to export all space and "current" to export the current space - */ - public String getMode() - { - return this.mode; - } - - /** - * Sets whether to export the current space or all spaces - * - * @param mode "all" to export all space and "current" to export the current space - */ - public void setMode(String mode) - { - this.mode = mode; - } - - /** - * Returns the encoding to use for the export - * - * @return The encoding - */ - public String getEncoding() - { - return this.encoding; - } - - /** - * Sets the encoding to use for the export package - * - * @param encoding The encoding - */ - public void setEncoding(String encoding) - { - this.encoding = encoding; - } - - /** - * Determines whether the import should run in the background - * - * @return true means the import will run in the background - */ - public boolean getRunInBackground() - { - return this.runInBackground; - } - - /** - * Determines whether the import will run in the background - * - * @param runInBackground true to run the import in the background - */ - public void setRunInBackground(boolean runInBackground) - { - this.runInBackground = runInBackground; - } - - /** - * Sets the BrowseBean instance to use to retrieve the current document - * - * @param browseBean BrowseBean instance - */ - public void setBrowseBean(BrowseBean browseBean) - { - this.browseBean = browseBean; - } - - /** - * Sets the action service - * - * @param actionService the action service - */ - public void setActionService(ActionService actionService) - { - this.actionService = actionService; - } - - protected ActionService getActionService() - { - if (actionService == null) - { - actionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getActionService(); - } - return actionService; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/admin/ImportDialog.java b/war/src/main/java/org/alfresco/web/bean/admin/ImportDialog.java deleted file mode 100644 index d643cc65df..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/admin/ImportDialog.java +++ /dev/null @@ -1,515 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.admin; - -import java.io.File; -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.model.SelectItem; - -import org.springframework.extensions.surf.util.I18NUtil; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.action.executer.ImporterActionExecuter; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.repo.transaction.RetryingTransactionHelper; -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.service.cmr.action.Action; -import org.alfresco.service.cmr.action.ActionService; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.ContentService; -import org.alfresco.service.cmr.repository.ContentWriter; -import org.alfresco.service.cmr.repository.DuplicateChildNodeNameException; -import org.alfresco.service.cmr.repository.MimetypeService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.FileUploadBean; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.repo.component.UICharsetSelector; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.extensions.config.Config; -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigService; -import org.springframework.extensions.surf.util.I18NUtil; - -/** - * Backing bean implementation for the Import dialog. - * - * @author gavinc - */ -public class ImportDialog extends BaseDialogBean -{ - private static final long serialVersionUID = -8563911447832447065L; - - private static final Log logger = LogFactory.getLog(ImportDialog.class); - - private static final String DEFAULT_OUTCOME = "dialog:close"; - - private static final String MSG_ERROR = "error_import"; - private static final String ERR_DUPLICATE_NAME = "system.err.duplicate_name"; - private static final String MSG_ERROR_NO_FILE = "error_import_no_file"; - private static final String MSG_ERROR_EMPTY_FILE = "error_import_empty_file"; - private static final String MSG_OK = "ok"; - private static final String MSG_IMPORT_TITLE = "import_title"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - transient private ActionService actionService; - transient private ContentService contentService; - transient private MimetypeService mimetypeService; - - private File file; - private String fileName; - private String encoding = "UTF-8"; - private boolean runInBackground = true; - private boolean highByteZip = false; - List encodings; - - /** - * Performs the import operation using the current state of the bean - * - * @return The outcome - */ - public String performImport(final FacesContext context, String outcome) - { - - - if (logger.isDebugEnabled()) - logger.debug("Called import for file: " + this.file); - - if (this.file != null && this.file.exists()) - { - // check the file actually has contents - if (this.file.length() > 0) - { - try - { - - RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(context); - RetryingTransactionCallback callback = new RetryingTransactionCallback() - { - public Object execute() throws Throwable - { - // first of all we need to add the uploaded ACP/ZIP file to the repository - NodeRef acpNodeRef = addFileToRepository(context); - - // build the action params map based on the bean's current state - Map params = new HashMap(2, 1.0f); - params.put(ImporterActionExecuter.PARAM_DESTINATION_FOLDER, browseBean.getActionSpace().getNodeRef()); - params.put(ImporterActionExecuter.PARAM_ENCODING, encoding); - - // build the action to execute - Action action = getActionService().createAction(ImporterActionExecuter.NAME, params); - if (action instanceof ImporterActionExecuter) - { - ((ImporterActionExecuter)action).setHighByteZip(highByteZip); - } - action.setExecuteAsynchronously(runInBackground); - - // execute the action on the ACP file - getActionService().executeAction(action, acpNodeRef); - - if (logger.isDebugEnabled()) - { - logger.debug("Executed import action with action params of " + params); - } - return null; - } - }; - txnHelper.doInTransaction(callback); - - // reset the bean - reset(); - } - catch (Throwable e) - { - if (e instanceof DuplicateChildNodeNameException) - { - String name = ((DuplicateChildNodeNameException)e).getName(); - String err_mess = MessageFormat.format(I18NUtil.getMessage(ERR_DUPLICATE_NAME), name); - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), MSG_ERROR), err_mess), e); - } - else - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), MSG_ERROR), e.toString()), e); - } - outcome = null; - ReportedException.throwIfNecessary(e); - } - } - else - { - Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), MSG_ERROR_EMPTY_FILE)); - outcome = null; - } - } - else - { - Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), MSG_ERROR_NO_FILE)); - outcome = null; - } - - return outcome; - } - - /** - * Action called when the dialog is cancelled, just resets the bean's state - * - * @return The outcome - */ - public String cancel() - { - reset(); - - return DEFAULT_OUTCOME; - } - - /** - * Resets the dialog state back to the default - */ - public void reset() - { - this.file = null; - this.fileName = null; - this.runInBackground = true; - - // delete the temporary file we uploaded earlier - if (this.file != null) - { - this.file.delete(); - } - - // remove the file upload bean from the session - FacesContext ctx = FacesContext.getCurrentInstance(); - ctx.getExternalContext().getSessionMap().remove(FileUploadBean.FILE_UPLOAD_BEAN_NAME); - } - - /** - * @return Returns the message to display when a file has been uploaded - */ - public String getFileUploadSuccessMsg() - { - String msg = Application.getMessage(FacesContext.getCurrentInstance(), "file_upload_success"); - return MessageFormat.format(msg, new Object[] {Utils.encode(getFileName())}); - } - - /** - * @return Returns the name of the file - */ - public String getFileName() - { - // try and retrieve the file and filename from the file upload bean - // representing the file we previously uploaded. - FacesContext ctx = FacesContext.getCurrentInstance(); - FileUploadBean fileBean = (FileUploadBean)ctx.getExternalContext().getSessionMap(). - get(FileUploadBean.FILE_UPLOAD_BEAN_NAME); - if (fileBean != null) - { - this.fileName = fileBean.getFileName(); - this.file = fileBean.getFile(); - } - - return this.fileName; - } - - /** - * @param fileName The name of the file - */ - public void setFileName(String fileName) - { - //do nothing required for JSF workflow - } - - /** - * Returns the encoding to use for the export - * - * @return The encoding - */ - /* public String getEncoding() - { - return this.encoding; - }*/ - - /** - * Sets the encoding to use for the export package - * - * @param encoding The encoding - */ -/* public void setEncoding(String encoding) - { - this.encoding = encoding; - }*/ - - /** - * Determines whether the import should run in the background - * - * @return true means the import will run in the background - */ - public boolean getRunInBackground() - { - return this.runInBackground; - } - - /** - * Determines whether the import will run in the background - * - * @param runInBackground true to run the import in the background - */ - public void setRunInBackground(boolean runInBackground) - { - this.runInBackground = runInBackground; - } - - /** - * @return the highByteZip encoding switch - */ - public boolean getHighByteZip() - { - return this.highByteZip; - } - - /** - * @param highByteZip the encoding switch for high-byte ZIP filenames to set - */ - public void setHighByteZip(boolean highByteZip) - { - this.highByteZip = highByteZip; - } - - /** - * Sets the action service - * - * @param actionService the action service - */ - public void setActionService(ActionService actionService) - { - this.actionService = actionService; - } - - protected ActionService getActionService() - { - if (actionService == null) - { - actionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getActionService(); - } - return actionService; - } - - /** - * Sets the content service - * - * @param contentService the content service - */ - public void setContentService(ContentService contentService) - { - this.contentService = contentService; - } - - protected ContentService getContentService() - { - if (contentService == null) - { - contentService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getContentService(); - } - return contentService; - } - - /** - * Sets the mimetype sevice - * - * @param mimetypeService the mimetype service - */ - public void setMimetypeService(MimetypeService mimetypeService) - { - this.mimetypeService = mimetypeService; - } - - protected MimetypeService getMimetypeService() - { - if (mimetypeService == null) - { - mimetypeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getMimetypeService(); - } - return mimetypeService; - } - - /** - * Adds the uploaded ACP/ZIP file to the repository - * - * @param context Faces context - * @return NodeRef representing the ACP/ZIP file in the repository - */ - private NodeRef addFileToRepository(FacesContext context) - { - // set the name for the new node - Map contentProps = new HashMap(1); - contentProps.put(ContentModel.PROP_NAME, this.fileName); - - // create the node to represent the zip file - String assocName = QName.createValidLocalName(this.fileName); - ChildAssociationRef assocRef = this.getNodeService().createNode( - this.browseBean.getActionSpace().getNodeRef(), ContentModel.ASSOC_CONTAINS, - QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, assocName), - ContentModel.TYPE_CONTENT, contentProps); - - NodeRef acpNodeRef = assocRef.getChildRef(); - - // apply the titled aspect to behave in the web client - String mimetype = this.getMimetypeService().guessMimetype(this.fileName); - Map titledProps = new HashMap(2, 1.0f); - titledProps.put(ContentModel.PROP_TITLE, this.fileName); - titledProps.put(ContentModel.PROP_DESCRIPTION, - MimetypeMap.MIMETYPE_ACP.equals(mimetype) ? - Application.getMessage(context, "import_acp_description") : - Application.getMessage(context, "import_zip_description")); - this.getNodeService().addAspect(acpNodeRef, ContentModel.ASPECT_TITLED, titledProps); - - // add the content to the node - ContentWriter writer = this.getContentService().getWriter(acpNodeRef, ContentModel.PROP_CONTENT, true); - writer.setEncoding("UTF-8"); - writer.setMimetype(mimetype); - writer.putContent(this.file); - - return acpNodeRef; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return performImport(context,outcome); - } - - @Override - public boolean getFinishButtonDisabled() - { - return getFileName() == null; - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_OK); - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - String name = Application.getMessage(fc, MSG_LEFT_QUOTE) - + browseBean.getActionSpace().getName() - + Application.getMessage(fc, MSG_RIGHT_QUOTE); - return MessageFormat.format(Application.getMessage(fc, MSG_IMPORT_TITLE), name); - } - - /** - * @return Returns the encoding currently selected - */ - public String getEncoding() - { - if (encoding == null) - { - ConfigService configSvc = Application.getConfigService(FacesContext.getCurrentInstance()); - Config config = configSvc.getConfig("Import Dialog"); - if (config != null) - { - ConfigElement defaultEncCfg = config.getConfigElement("default-encoding"); - if (defaultEncCfg != null) - { - String value = defaultEncCfg.getValue(); - if (value != null) - { - encoding = value.trim(); - } - } - } - if (encoding == null || encoding.length() == 0) - { - // if not configured, set to a sensible default for most character sets - encoding = "UTF-8"; - } - } - return encoding; - } - - /** - * @param encoding the document's encoding - */ - public void setEncoding(String encoding) - { - this.encoding = encoding; - } - - public List getEncodings() - { - if ((this.encodings == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - FacesContext context = FacesContext.getCurrentInstance(); - - this.encodings = new ArrayList(3); - - ConfigService svc = Application.getConfigService(context); - Config cfg = svc.getConfig("Import Dialog"); - if (cfg != null) - { - ConfigElement typesCfg = cfg.getConfigElement("encodings"); - if (typesCfg != null) - { - for (ConfigElement child : typesCfg.getChildren()) - { - String encoding = child.getAttribute("name"); - if (encoding != null) - { - this.encodings.add(new SelectItem(encoding, encoding)); - } - } - } - else - { - logger.warn("Could not find 'encodings' configuration element"); - } - } - else - { - encodings = UICharsetSelector.getCharsetEncodingList(); - } - } - - return this.encodings; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/admin/ShowSystemInfoDialog.java b/war/src/main/java/org/alfresco/web/bean/admin/ShowSystemInfoDialog.java deleted file mode 100644 index 793dd4829a..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/admin/ShowSystemInfoDialog.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.admin; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.AboutBean; -import org.alfresco.web.bean.dialog.BaseDialogBean; - -/** - * Implementation for the SystemInfo dialog. - * - * @author gavinc - */ -public class ShowSystemInfoDialog extends BaseDialogBean -{ - private static final long serialVersionUID = 1328587489092603676L; - - private static final String MSG_CURRENT_USER = "current_user"; - private static final String MSG_CLOSE = "close"; - private static final String MSG_VERSION = "version"; - - protected AboutBean aboutBean; - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - public void setAboutBean(AboutBean aboutBean) - { - this.aboutBean = aboutBean; - } - - @Override - public String getContainerSubTitle() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CURRENT_USER) + ": " + - this.navigator.getCurrentUser().getUserName(); - } - - @Override - public String getContainerDescription() - { - StringBuilder builder = new StringBuilder(Application.getMessage( - FacesContext.getCurrentInstance(), MSG_VERSION)); - builder.append(": "); - builder.append(this.aboutBean.getEdition()); - builder.append(" - v"); - builder.append(this.aboutBean.getVersion()); - - return builder.toString(); - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/ajax/CategoryBrowserPluginBean.java b/war/src/main/java/org/alfresco/web/bean/ajax/CategoryBrowserPluginBean.java deleted file mode 100644 index e9ea7d057e..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/ajax/CategoryBrowserPluginBean.java +++ /dev/null @@ -1,354 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.ajax; - -import java.io.IOException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.search.CategoryService; -import org.alfresco.service.namespace.RegexQNamePattern; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.data.IDataContainer; -import org.alfresco.web.data.QuickSort; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.repo.component.UITree.TreeNode; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class CategoryBrowserPluginBean implements Serializable -{ - private static final long serialVersionUID = -1493808456969763500L; - - public static final String BEAN_NAME = "CategoryBrowserPluginBean"; - - private static final Log logger = LogFactory.getLog(CategoryBrowserPluginBean.class); - - transient private CategoryService categoryService; - transient private NodeService nodeService; - - private List categoryRootNodes; - private Map categoryNodes; - protected NodeRef previouslySelectedNode; - - /** - * @param categoryService - * the categoryService to set - */ - public void setCategoryService(CategoryService categoryService) - { - this.categoryService = categoryService; - } - - /** - * @return the categoryService - */ - private CategoryService getCategoryService() - { - //check for null in cluster environment - if(categoryService == null) - { - categoryService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getCategoryService(); - } - return categoryService; - } - - /** - * @param nodeService - * the nodeService to set - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - /** - * @return the nodeService - */ - private NodeService getNodeService() - { - //check for null in cluster environment - if(nodeService == null) - { - nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - } - return nodeService; - } - - public List getCategoryRootNodes() - { - if (this.categoryRootNodes == null) - { - this.categoryRootNodes = new ArrayList(); - this.categoryNodes = new HashMap(); - - UserTransaction tx = null; - try - { - tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true); - tx.begin(); - - Collection childRefs = this.getCategoryService().getRootCategories( - Repository.getStoreRef(), ContentModel.ASPECT_GEN_CLASSIFIABLE); - - for (ChildAssociationRef ref : childRefs) - { - NodeRef child = ref.getChildRef(); - TreeNode node = createTreeNode(child); - this.categoryRootNodes.add(node); - this.categoryNodes.put(node.getNodeRef(), node); - } - - tx.commit(); - } - catch (Throwable err) - { - Utils.addErrorMessage("NavigatorPluginBean exception in getCompanyHomeRootNodes()", err); - try - { - if (tx != null) - { - tx.rollback(); - } - } - catch (Exception tex) - { - } - } - } - - return this.categoryRootNodes; - } - - protected Map getNodesMap() - { - return this.categoryNodes; - } - - /** - * Retrieves the child folders for the noderef given in the 'noderef' parameter and caches the nodes against the area - * in the 'area' parameter. - */ - public void retrieveChildren() throws IOException - { - FacesContext context = FacesContext.getCurrentInstance(); - ResponseWriter out = context.getResponseWriter(); - - UserTransaction tx = null; - try - { - tx = Repository.getUserTransaction(context, true); - tx.begin(); - - Map params = context.getExternalContext().getRequestParameterMap(); - String nodeRefStr = (String) params.get("nodeRef"); - - // work out which list to cache the nodes in - Map currentNodes = getNodesMap(); - - if (nodeRefStr != null && currentNodes != null) - { - // get the given node's details - NodeRef parentNodeRef = new NodeRef(nodeRefStr); - TreeNode parentNode = currentNodes.get(parentNodeRef.toString()); - parentNode.setExpanded(true); - - if (logger.isDebugEnabled()) - logger.debug("retrieving children for noderef: " + parentNodeRef); - - // remove any existing children as the latest ones will be added - // below - parentNode.removeChildren(); - - // get all the child folder objects for the parent - List childRefs = this.getNodeService().getChildAssocs(parentNodeRef, - ContentModel.ASSOC_SUBCATEGORIES, RegexQNamePattern.MATCH_ALL); - List sortedNodes = new ArrayList(); - for (ChildAssociationRef ref : childRefs) - { - NodeRef nodeRef = ref.getChildRef(); - logger.debug("retrieving child : " + nodeRef); - // build the XML representation of the child node - TreeNode childNode = createTreeNode(nodeRef); - parentNode.addChild(childNode); - currentNodes.put(childNode.getNodeRef(), childNode); - sortedNodes.add(childNode); - } - - // order the tree nodes by the tree label - if (sortedNodes.size() > 1) - { - QuickSort sorter = new QuickSort(sortedNodes, "name", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - } - - // generate the XML representation - StringBuilder xml = new StringBuilder( - ""); - for (TreeNode childNode : sortedNodes) - { - xml.append(childNode.toXML()); - } - xml.append(""); - - // send the generated XML back to the tree - out.write(xml.toString()); - - if (logger.isDebugEnabled()) - logger.debug("returning XML: " + xml.toString()); - } - - // commit the transaction - tx.commit(); - } - catch (Throwable err) - { - try - { - if (tx != null) - { - tx.rollback(); - } - } - catch (Exception tex) - { - } - } - } - - /** - * Sets the state of the node given in the 'nodeRef' parameter to collapsed - */ - public void nodeCollapsed() throws IOException - { - FacesContext context = FacesContext.getCurrentInstance(); - ResponseWriter out = context.getResponseWriter(); - Map params = context.getExternalContext().getRequestParameterMap(); - String nodeRefStr = (String) params.get("nodeRef"); - - // work out which list to cache the nodes in - Map currentNodes = getNodesMap(); - - if (nodeRefStr != null && currentNodes != null) - { - TreeNode treeNode = currentNodes.get(nodeRefStr); - if (treeNode != null) - { - treeNode.setExpanded(false); - - // we need to return something for the client to be happy! - out.write(""); - - if (logger.isDebugEnabled()) - logger.debug("Set node " + treeNode + " to collapsed state"); - } - } - } - - public void selectNode(NodeRef selectedNode, String area) - { - // if there is a currently selected node, get hold of - // it (from any of the areas) and reset to unselected - if (this.previouslySelectedNode != null) - { - TreeNode node = this.categoryNodes.get(this.previouslySelectedNode.toString()); - if (node != null) - { - node.setSelected(false); - } - } - - // find the node just selected and set its state to selected - if (selectedNode != null) - { - TreeNode node = this.categoryNodes.get(selectedNode.toString()); - if (node != null) - { - node.setSelected(true); - } - } - - this.previouslySelectedNode = selectedNode; - - if (logger.isDebugEnabled()) - logger.debug("Selected node: " + selectedNode); - } - - /** - * Resets the selected node - */ - public void resetSelectedNode() - { - if (this.previouslySelectedNode != null) - { - TreeNode node = this.categoryNodes.get(this.previouslySelectedNode.toString()); - if (node != null) - { - node.setSelected(false); - } - } - if (logger.isDebugEnabled()) - logger.debug("Reset selected node: " + this.previouslySelectedNode); - } - - /** - * Resets all the caches held by the bean. - */ - public void reset() - { - this.categoryNodes = null; - this.categoryRootNodes = null; - - resetSelectedNode(); - } - - /** - * Creates a TreeNode object from the given NodeRef - * - * @param nodeRef - * The NodeRef to create the TreeNode from - */ - protected TreeNode createTreeNode(NodeRef nodeRef) - { - TreeNode node = new TreeNode(nodeRef.toString(), Repository.getNameForNode(this.getNodeService(), nodeRef), - (String) this.getNodeService().getProperty(nodeRef, ApplicationModel.PROP_ICON)); - - return node; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/ajax/ContentUpdateBean.java b/war/src/main/java/org/alfresco/web/bean/ajax/ContentUpdateBean.java deleted file mode 100644 index 24bc6741af..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/ajax/ContentUpdateBean.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.ajax; - -import java.io.File; -import java.io.Serializable; -import java.util.List; - -import javax.faces.context.ExternalContext; -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; -import javax.servlet.http.HttpServletRequest; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.ContentWriter; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.util.TempFileProvider; -import org.alfresco.web.app.servlet.ajax.InvokeCommand; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.util.XMLUtil; -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; -import org.apache.commons.fileupload.servlet.ServletFileUpload; -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - -/** - * Bean managing the ajax servlet upload of a multi-part form containing file content - * to replace the content of a node within the repository. - * - * @author Mike Hatfield - */ -public class ContentUpdateBean implements Serializable -{ - private static final long serialVersionUID = -7209326198823950952L; - - private static Log logger = LogFactory.getLog(ContentUpdateBean.class); - - /** - * Ajax method to update file content. A multi-part form is required as the input. - * - * "return-page" = javascript to execute on return from the upload request - * "nodeRef" = the nodeRef of the item to update the content of - * - * @throws Exception - */ - @InvokeCommand.ResponseMimetype(value=MimetypeMap.MIMETYPE_HTML) - public void updateFile() throws Exception - { - FacesContext fc = FacesContext.getCurrentInstance(); - ExternalContext externalContext = fc.getExternalContext(); - HttpServletRequest request = (HttpServletRequest)externalContext.getRequest(); - - ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); - upload.setHeaderEncoding("UTF-8"); - - List fileItems = upload.parseRequest(request); - String strNodeRef = null; - String strFilename = null; - String strReturnPage = null; - File file = null; - - for (FileItem item : fileItems) - { - if (item.isFormField() && item.getFieldName().equals("return-page")) - { - strReturnPage = item.getString(); - } - else if (item.isFormField() && item.getFieldName().equals("nodeRef")) - { - strNodeRef = item.getString(); - } - else - { - strFilename = FilenameUtils.getName(item.getName()); - file = TempFileProvider.createTempFile("alfresco", ".upload"); - item.write(file); - } - } - - if (logger.isDebugEnabled()) - logger.debug("Ajax content update request: " + strFilename + " to nodeRef: " + strNodeRef + " return page: " + strReturnPage); - - try - { - if (file != null && strNodeRef != null && strNodeRef.length() != 0) - { - NodeRef nodeRef = new NodeRef(strNodeRef); - if (nodeRef != null) - { - ServiceRegistry services = Repository.getServiceRegistry(fc); - - // get a writer for the content and put the file - ContentWriter writer = services.getContentService().getWriter(nodeRef, ContentModel.PROP_CONTENT, true); - writer.putContent(file); - } - } - } - catch (Exception e) - { - strReturnPage = strReturnPage.replace("${UPLOAD_ERROR}", e.getMessage()); - } - - Document result = XMLUtil.newDocument(); - Element htmlEl = result.createElement("html"); - result.appendChild(htmlEl); - Element bodyEl = result.createElement("body"); - htmlEl.appendChild(bodyEl); - - Element scriptEl = result.createElement("script"); - bodyEl.appendChild(scriptEl); - scriptEl.setAttribute("type", "text/javascript"); - Node scriptText = result.createTextNode(strReturnPage); - scriptEl.appendChild(scriptText); - - if (logger.isDebugEnabled()) - logger.debug("Content update request complete."); - - ResponseWriter out = fc.getResponseWriter(); - XMLUtil.print(result, out); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/ajax/FileUploadBean.java b/war/src/main/java/org/alfresco/web/bean/ajax/FileUploadBean.java deleted file mode 100644 index 3b4c8d006c..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/ajax/FileUploadBean.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.ajax; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.Serializable; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.StringTokenizer; - -import javax.faces.context.ExternalContext; -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; -import javax.servlet.http.HttpServletRequest; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.repo.content.filestore.FileContentReader; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.model.FileInfo; -import org.alfresco.service.cmr.repository.ContentReader; -import org.alfresco.service.cmr.repository.ContentWriter; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter; -import org.alfresco.service.namespace.QName; -import org.alfresco.util.TempFileProvider; -import org.springframework.extensions.surf.util.URLDecoder; -import org.alfresco.web.app.servlet.BaseServlet; -import org.alfresco.web.app.servlet.ajax.InvokeCommand; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.util.XMLUtil; -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; -import org.apache.commons.fileupload.servlet.ServletFileUpload; -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - -/** - * Bean managing the ajax servlet upload of a multi-part form containing file content - * to be added at a specific path in the server. - * - * @author Kevin Roast - */ -public class FileUploadBean implements Serializable -{ - private static final long serialVersionUID = 4555828718375916674L; - - private static Log logger = LogFactory.getLog(FileUploadBean.class); - - /** - * Ajax method to upload file content. A multi-part form is required as the input. - * - * "return-page" = javascript to execute on return from the upload request - * "currentPath" = the cm:name based server path to upload the content into - * and the file item content. - * - * @throws Exception - */ - @InvokeCommand.ResponseMimetype(value=MimetypeMap.MIMETYPE_HTML) - public void uploadFile() throws Exception - { - FacesContext fc = FacesContext.getCurrentInstance(); - ExternalContext externalContext = fc.getExternalContext(); - HttpServletRequest request = (HttpServletRequest)externalContext.getRequest(); - - ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); - upload.setHeaderEncoding("UTF-8"); - - List fileItems = upload.parseRequest(request); - FileUploadBean bean = new FileUploadBean(); - String currentPath = null; - String filename = null; - String returnPage = null; - File file = null; - - for (FileItem item : fileItems) - { - if (item.isFormField() && item.getFieldName().equals("return-page")) - { - returnPage = item.getString(); - } - else if (item.isFormField() && item.getFieldName().equals("currentPath")) - { - currentPath = URLDecoder.decode(item.getString()); - } - else - { - filename = FilenameUtils.getName(item.getName()); - file = TempFileProvider.createTempFile("alfresco", ".upload"); - item.write(file); - } - } - - if (logger.isDebugEnabled()) - logger.debug("Ajax file upload request: " + filename + " to path: " + currentPath + " return page: " + returnPage); - - try - { - if (file != null && currentPath != null && currentPath.length() != 0) - { - NodeRef containerRef = pathToNodeRef(fc, currentPath); - if (containerRef != null) - { - // Guess the mimetype - String mimetype = Repository.getMimeTypeForFileName(fc, filename); - - // Now guess the encoding - String encoding = "UTF-8"; - InputStream is = null; - try - { - is = new BufferedInputStream(new FileInputStream(file)); - encoding = Repository.guessEncoding(fc, is, mimetype); - } - catch (Throwable e) - { - // Bad as it is, it's not terminal - logger.error("Failed to guess character encoding of file: " + file, e); - } - finally - { - if (is != null) - { - try { is.close(); } catch (Throwable e) {} - } - } - - // Try and extract metadata from the file - ContentReader cr = new FileContentReader(file); - cr.setMimetype(mimetype); - - // create properties for content type - String author = null; - String title = null; - String description = null; - Map contentProps = new HashMap(5, 1.0f); - if (Repository.extractMetadata(fc, cr, contentProps)) - { - author = (String)(contentProps.get(ContentModel.PROP_AUTHOR)); - title = DefaultTypeConverter.INSTANCE.convert(String.class, contentProps.get(ContentModel.PROP_TITLE)); - description = DefaultTypeConverter.INSTANCE.convert(String.class, contentProps.get(ContentModel.PROP_DESCRIPTION)); - } - - // default the title to the file name if not set - if (title == null) - { - title = filename; - } - - ServiceRegistry services = Repository.getServiceRegistry(fc); - FileInfo fileInfo = services.getFileFolderService().create( - containerRef, filename, ContentModel.TYPE_CONTENT); - NodeRef fileNodeRef = fileInfo.getNodeRef(); - - // set the author aspect - if (author != null) - { - Map authorProps = new HashMap(1, 1.0f); - authorProps.put(ContentModel.PROP_AUTHOR, author); - services.getNodeService().addAspect(fileNodeRef, ContentModel.ASPECT_AUTHOR, authorProps); - } - - // apply the titled aspect - title and description - Map titledProps = new HashMap(2, 1.0f); - titledProps.put(ContentModel.PROP_TITLE, title); - titledProps.put(ContentModel.PROP_DESCRIPTION, description); - services.getNodeService().addAspect(fileNodeRef, ContentModel.ASPECT_TITLED, titledProps); - - // get a writer for the content and put the file - ContentWriter writer = services.getContentService().getWriter(fileNodeRef, ContentModel.PROP_CONTENT, true); - writer.setMimetype(mimetype); - writer.setEncoding(encoding); - writer.putContent(file); - } - } - } - catch (Exception e) - { - returnPage = returnPage.replace("${UPLOAD_ERROR}", e.getMessage()); - } - finally - { - if(file != null) - { - logger.debug("delete temporary file:" + file.getPath()); - // Delete the temporary file - file.delete(); - } - } - - Document result = XMLUtil.newDocument(); - Element htmlEl = result.createElement("html"); - result.appendChild(htmlEl); - Element bodyEl = result.createElement("body"); - htmlEl.appendChild(bodyEl); - - Element scriptEl = result.createElement("script"); - bodyEl.appendChild(scriptEl); - scriptEl.setAttribute("type", "text/javascript"); - Node scriptText = result.createTextNode(returnPage); - scriptEl.appendChild(scriptText); - - if (logger.isDebugEnabled()) - { - logger.debug("File upload request complete."); - } - ResponseWriter out = fc.getResponseWriter(); - XMLUtil.print(result, out); - } - - static NodeRef pathToNodeRef(FacesContext fc, String path) - { - // convert cm:name based path to a NodeRef - StringTokenizer t = new StringTokenizer(path, "/"); - int tokenCount = t.countTokens(); - String[] elements = new String[tokenCount]; - for (int i=0; i. - * #L% - */ -package org.alfresco.web.bean.ajax; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.service.cmr.model.FileExistsException; -import org.alfresco.service.cmr.model.FileFolderService; -import org.alfresco.service.cmr.model.FileInfo; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.servlet.ajax.InvokeCommand; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.spaces.CreateSpaceWizard; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean backing the ajax requests from the MySpaces portlet webscript. - * - * @author Kevin Roast - */ -public class MySpacesBean implements Serializable -{ - private static final long serialVersionUID = -5684182834188359483L; - - private static Log logger = LogFactory.getLog(MySpacesBean.class); - - @InvokeCommand.ResponseMimetype(value=MimetypeMap.MIMETYPE_HTML) - public void createSpace() throws Exception - { - FacesContext fc = FacesContext.getCurrentInstance(); - ResponseWriter out = fc.getResponseWriter(); - - Map requestMap = fc.getExternalContext().getRequestParameterMap(); - String path = (String)requestMap.get("path"); - String name = (String)requestMap.get("name"); - String title = (String)requestMap.get("title"); - String description = (String)requestMap.get("description"); - - if (logger.isDebugEnabled()) - logger.debug("MySpacesBean.createSpace() path=" + path + " name=" + name + - " title=" + title + " description=" + description); - - try - { - if (path != null && name != null) - { - NodeRef containerRef = FileUploadBean.pathToNodeRef(fc, path); - if (containerRef != null) - { - NodeService nodeService = Repository.getServiceRegistry(fc).getNodeService(); - FileFolderService ffService = Repository.getServiceRegistry(fc).getFileFolderService(); - FileInfo folderInfo = ffService.create(containerRef, name, ContentModel.TYPE_FOLDER); - if (logger.isDebugEnabled()) - logger.debug("Created new folder: " + folderInfo.getNodeRef().toString()); - - // apply the uifacets aspect - icon, title and description properties - Map uiFacetsProps = new HashMap(4, 1.0f); - uiFacetsProps.put(ApplicationModel.PROP_ICON, CreateSpaceWizard.DEFAULT_SPACE_ICON_NAME); - uiFacetsProps.put(ContentModel.PROP_TITLE, title); - uiFacetsProps.put(ContentModel.PROP_DESCRIPTION, description); - nodeService.addAspect(folderInfo.getNodeRef(), ApplicationModel.ASPECT_UIFACETS, uiFacetsProps); - - out.write("OK: " + folderInfo.getNodeRef().toString()); - } - } - } - catch (FileExistsException ferr) - { - out.write("ERROR: A file with that name already exists."); - } - catch (Throwable err) - { - out.write("ERROR: " + err.getMessage()); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/ajax/NavigatorPluginBean.java b/war/src/main/java/org/alfresco/web/bean/ajax/NavigatorPluginBean.java deleted file mode 100644 index 43c64365d5..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/ajax/NavigatorPluginBean.java +++ /dev/null @@ -1,749 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.ajax; - -import java.io.IOException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.dictionary.TypeDefinition; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.namespace.QName; -import org.alfresco.service.namespace.RegexQNamePattern; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.IContextListener; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.BrowseBean; -import org.alfresco.web.bean.NavigationBean; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.data.IDataContainer; -import org.alfresco.web.data.QuickSort; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.repo.component.UITree.TreeNode; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean used by the navigator component to manage the tree data. - * - * @author gavinc - */ -public class NavigatorPluginBean implements IContextListener,Serializable -{ - private static final long serialVersionUID = 5837326721916936115L; - - public static final String BEAN_NAME = "NavigatorPluginBean"; - - protected List companyHomeRootNodes; - protected List myHomeRootNodes; - protected List guestHomeRootNodes; - protected Map companyHomeNodes; - protected Map myHomeNodes; - protected Map guestHomeNodes; - protected NodeRef previouslySelectedNode; - - transient private NodeService nodeService; - transient private NodeService internalNodeService; - transient private DictionaryService dictionaryService; - - private static final Log logger = LogFactory.getLog(NavigatorPluginBean.class); - - public NavigatorPluginBean() - { - UIContextService.getInstance(FacesContext.getCurrentInstance()).registerBean(this); - } - - // ------------------------------------------------------------------------------ - // AJAX handler methods - - /** - * Retrieves the child folders for the noderef given in the - * 'noderef' parameter and caches the nodes against the area in - * the 'area' parameter. - */ - public void retrieveChildren() throws IOException - { - FacesContext context = FacesContext.getCurrentInstance(); - ResponseWriter out = context.getResponseWriter(); - - UserTransaction tx = null; - try - { - tx = Repository.getUserTransaction(context, true); - tx.begin(); - - Map params = context.getExternalContext().getRequestParameterMap(); - String nodeRefStr = (String)params.get("nodeRef"); - String area = (String)params.get("area"); - - if (logger.isDebugEnabled()) - logger.debug("retrieveChildren: area = " + area + ", nodeRef = " + nodeRefStr); - - // work out which list to cache the nodes in - Map currentNodes = getNodesMapForArea(area); - - if (nodeRefStr != null && currentNodes != null) - { - // get the given node's details - NodeRef parentNodeRef = new NodeRef(nodeRefStr); - TreeNode parentNode = currentNodes.get(parentNodeRef.toString()); - parentNode.setExpanded(true); - - if (logger.isDebugEnabled()) - logger.debug("retrieving children for noderef: " + parentNodeRef); - - // remove any existing children as the latest ones will be added below - parentNode.removeChildren(); - - // get all the child folder objects for the parent - List childRefs = this.getNodeService().getChildAssocs(parentNodeRef, - ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL); - List sortedNodes = new ArrayList(); - for (ChildAssociationRef ref: childRefs) - { - NodeRef nodeRef = ref.getChildRef(); - - if (isAddableChild(nodeRef)) - { - // build the XML representation of the child node - TreeNode childNode = createTreeNode(nodeRef); - parentNode.addChild(childNode); - currentNodes.put(childNode.getNodeRef(), childNode); - sortedNodes.add(childNode); - } - } - - // order the tree nodes by the tree label - if (sortedNodes.size() > 1) - { - QuickSort sorter = new QuickSort(sortedNodes, "name", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - } - - // generate the XML representation - StringBuilder xml = new StringBuilder(""); - for (TreeNode childNode : sortedNodes) - { - xml.append(childNode.toXML()); - } - xml.append(""); - - // send the generated XML back to the tree - out.write(xml.toString()); - - if (logger.isDebugEnabled()) - logger.debug("returning XML: " + xml.toString()); - } - - // commit the transaction - tx.commit(); - } - catch (Throwable err) - { - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - } - - /** - * Sets the state of the node given in the 'nodeRef' parameter to collapsed - */ - public void nodeCollapsed() throws IOException - { - FacesContext context = FacesContext.getCurrentInstance(); - ResponseWriter out = context.getResponseWriter(); - Map params = context.getExternalContext().getRequestParameterMap(); - String nodeRefStr = (String)params.get("nodeRef"); - String area = (String)params.get("area"); - - if (logger.isDebugEnabled()) - logger.debug("nodeCollapsed: area = " + area + ", nodeRef = " + nodeRefStr); - - // work out which list to cache the nodes in - Map currentNodes = getNodesMapForArea(area); - - if (nodeRefStr != null && currentNodes != null) - { - TreeNode treeNode = currentNodes.get(nodeRefStr); - if (treeNode != null) - { - treeNode.setExpanded(false); - - // we need to return something for the client to be happy! - out.write(""); - - if (logger.isDebugEnabled()) - logger.debug("Set node " + treeNode + " to collapsed state"); - } - } - } - - // ------------------------------------------------------------------------------ - // IContextListener implementation - - /** - * @see org.alfresco.web.app.context.IContextListener#contextUpdated() - */ - public void contextUpdated() - { - // nothing to do - } - - /** - * @see org.alfresco.web.app.context.IContextListener#areaChanged() - */ - public void areaChanged() - { - // nothing to do - - // NOTE: The code below is WIP for synchronizing the tree with - // the main navigation area of the application. - - /* - this.resetSelectedNode(); - */ - } - - /** - * @see org.alfresco.web.app.context.IContextListener#spaceChanged() - */ - public void spaceChanged() - { - // nothing to do - - // NOTE: The code below is WIP for synchronizing the tree with - // the main navigation area of the application. - - /* - NavigationBean navBean = getNavigationBean(); - if (navBean != null) - { - // get the current area and the new parent - String area = navBean.getToolbarLocation(); - Node parent = navBean.getDispatchContextNode(); - - if (parent != null) - { - if (logger.isDebugEnabled()) - logger.debug("Space changed, parent node is now: " + parent.getNodeRef().toString()); - - // select the new parent node - selectNode(parent.getNodeRef(), area); - - // get the nodes for the current area - BrowseBean browseBean = getBrowseBean(); - Map currentNodes = getNodesMapForArea(area); - - if (browseBean != null && currentNodes != null) - { - // find the parent node in the cache - TreeNode parentNode = currentNodes.get(parent.getNodeRef().toString()); - if (parentNode != null) - { - // reset the previously selected node - resetSelectedNode(); - - // set the parent to expanded and selected - parentNode.setExpanded(true); - selectNode(parent.getNodeRef(), area); - - for (Node child : browseBean.getNodes()) - { - NodeRef nodeRef = child.getNodeRef(); - - // check the child is applicable for the tree and is not already - // in the cache - if (isAddableChild(nodeRef) && - currentNodes.containsKey(nodeRef.toString()) == false) - { - // create the child tree node and add to the cache - TreeNode childNode = createTreeNode(nodeRef); - parentNode.addChild(childNode); - currentNodes.put(childNode.getNodeRef(), childNode); - } - } - } - } - } - } - */ - } - - // ------------------------------------------------------------------------------ - // Bean getters and setters - - /** - * Returns the root nodes for the company home panel. - *

- * As the user expands and collapses nodes in the client this - * cache will be updated with the appropriate nodes and states. - *

- * - * @return List of root nodes for the company home panel - */ - public List getCompanyHomeRootNodes() - { - if (this.companyHomeRootNodes == null) - { - this.companyHomeRootNodes = new ArrayList(); - this.companyHomeNodes = new HashMap(); - - UserTransaction tx = null; - try - { - FacesContext fc = FacesContext.getCurrentInstance(); - tx = Repository.getUserTransaction(fc, true); - tx.begin(); - - // query for the child nodes of company home - NodeRef root = new NodeRef(Repository.getStoreRef(), Application.getCompanyRootId(fc)); - List childRefs = this.getNodeService().getChildAssocs(root, - ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL); - - for (ChildAssociationRef ref: childRefs) - { - NodeRef child = ref.getChildRef(); - - if (isAddableChild(child)) - { - TreeNode node = createTreeNode(child); - this.companyHomeRootNodes.add(node); - this.companyHomeNodes.put(node.getNodeRef(), node); - } - } - - tx.commit(); - } - catch (Throwable err) - { - Utils.addErrorMessage("NavigatorPluginBean exception in getCompanyHomeRootNodes()", err); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - } - - return this.companyHomeRootNodes; - } - - /** - * Returns the root nodes for the my home panel. - *

- * As the user expands and collapses nodes in the client this - * cache will be updated with the appropriate nodes and states. - *

- * - * @return List of root nodes for the my home panel - */ - public List getMyHomeRootNodes() - { - if (this.myHomeRootNodes == null) - { - this.myHomeRootNodes = new ArrayList(); - this.myHomeNodes = new HashMap(); - - UserTransaction tx = null; - try - { - tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true); - tx.begin(); - - // query for the child nodes of the user's home - NodeRef root = new NodeRef(Repository.getStoreRef(), - Application.getCurrentUser(FacesContext.getCurrentInstance()).getHomeSpaceId()); - List childRefs = this.getNodeService().getChildAssocs(root, - ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL); - - for (ChildAssociationRef ref: childRefs) - { - NodeRef child = ref.getChildRef(); - - if (isAddableChild(child)) - { - TreeNode node = createTreeNode(child); - this.myHomeRootNodes.add(node); - this.myHomeNodes.put(node.getNodeRef(), node); - } - } - - tx.commit(); - } - catch (Throwable err) - { - Utils.addErrorMessage("NavigatorPluginBean exception in getMyHomeRootNodes()", err); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - } - - return this.myHomeRootNodes; - } - - /** - * Returns the root nodes for the guest home panel. - *

- * As the user expands and collapses nodes in the client this - * cache will be updated with the appropriate nodes and states. - *

- * - * @return List of root nodes for the guest home panel - */ - public List getGuestHomeRootNodes() - { - if (this.guestHomeRootNodes == null) - { - this.guestHomeRootNodes = new ArrayList(); - this.guestHomeNodes = new HashMap(); - - UserTransaction tx = null; - try - { - tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true); - tx.begin(); - - // query for the child nodes of the guest home space - NavigationBean navBean = getNavigationBean(); - if (navBean != null) - { - NodeRef root = navBean.getGuestHomeNode().getNodeRef(); - List childRefs = this.getNodeService().getChildAssocs(root, - ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL); - - for (ChildAssociationRef ref: childRefs) - { - NodeRef child = ref.getChildRef(); - - if (isAddableChild(child)) - { - TreeNode node = createTreeNode(child); - this.guestHomeRootNodes.add(node); - this.guestHomeNodes.put(node.getNodeRef(), node); - } - } - } - - tx.commit(); - } - catch (Throwable err) - { - Utils.addErrorMessage("NavigatorPluginBean exception in getGuestHomeRootNodes()", err); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - } - - return this.guestHomeRootNodes; - } - - /** - * @param nodeService The NodeService to set. - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - private NodeService getNodeService() - { - if (nodeService == null) - { - nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - } - return nodeService; - } - - /** - * @param internalNodeService The internalNodeService to set. - */ - public void setInternalNodeService(NodeService internalNodeService) - { - this.internalNodeService = internalNodeService; - } - - /** - * @return the internalNodeService - */ - private NodeService getInternalNodeService() - { - if (this.internalNodeService == null) { - this.internalNodeService = (NodeService) FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), "nodeService"); - } - return this.internalNodeService; - } - - /** - * @param dictionaryService The DictionaryService to set. - */ - public void setDictionaryService(DictionaryService dictionaryService) - { - this.dictionaryService = dictionaryService; - } - - private DictionaryService getDictionaryService() - { - if (dictionaryService == null) - { - dictionaryService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getDictionaryService(); - } - return dictionaryService; - } - - // ------------------------------------------------------------------------------ - // Helper methods - - /** - * Sets the currently selected node in the tree - * - * @param selectedNode The node that has been selected - */ - public void selectNode(NodeRef selectedNode, String area) - { - // if there is a currently selected node, get hold of - // it (from any of the areas) and reset to unselected - if (this.previouslySelectedNode != null) - { - if (NavigationBean.LOCATION_COMPANY.equals(area) && - this.companyHomeNodes != null) - { - TreeNode node = this.companyHomeNodes.get(this.previouslySelectedNode.toString()); - if (node != null) - { - node.setSelected(false); - } - } - else if (NavigationBean.LOCATION_HOME.equals(area) && - this.myHomeNodes != null) - { - TreeNode node = this.myHomeNodes.get(this.previouslySelectedNode.toString()); - if (node != null) - { - node.setSelected(false); - } - } - else if (NavigationBean.LOCATION_GUEST.equals(area) && - this.guestHomeNodes != null) - { - TreeNode node = this.guestHomeNodes.get(this.previouslySelectedNode.toString()); - if (node != null) - { - node.setSelected(false); - } - } - } - - // find the node just selected and set its state to selected - if (selectedNode != null) - { - if (NavigationBean.LOCATION_COMPANY.equals(area) && - this.companyHomeNodes != null) - { - TreeNode node = this.companyHomeNodes.get(selectedNode.toString()); - if (node != null) - { - node.setSelected(true); - } - } - else if (NavigationBean.LOCATION_HOME.equals(area) && - this.myHomeNodes != null) - { - TreeNode node = this.myHomeNodes.get(selectedNode.toString()); - if (node != null) - { - node.setSelected(true); - } - } - else if (NavigationBean.LOCATION_GUEST.equals(area) && - this.guestHomeNodes != null) - { - TreeNode node = this.guestHomeNodes.get(selectedNode.toString()); - if (node != null) - { - node.setSelected(true); - } - } - } - - this.previouslySelectedNode = selectedNode; - - if (logger.isDebugEnabled()) - logger.debug("Selected node: " + selectedNode); - } - - /** - * Resets the selected node - */ - public void resetSelectedNode() - { - if (this.previouslySelectedNode != null) - { - if (this.companyHomeNodes != null) - { - TreeNode node = this.companyHomeNodes.get(this.previouslySelectedNode.toString()); - if (node != null) - { - node.setSelected(false); - } - } - if (this.myHomeNodes != null) - { - TreeNode node = this.myHomeNodes.get(this.previouslySelectedNode.toString()); - if (node != null) - { - node.setSelected(false); - } - } - if (this.guestHomeNodes != null) - { - TreeNode node = this.guestHomeNodes.get(this.previouslySelectedNode.toString()); - if (node != null) - { - node.setSelected(false); - } - } - - if (logger.isDebugEnabled()) - logger.debug("Reset selected node: " + this.previouslySelectedNode); - } - } - - /** - * Resets all the caches held by the bean. - */ - public void reset() - { - this.companyHomeNodes = null; - this.companyHomeRootNodes = null; - this.myHomeNodes = null; - this.myHomeRootNodes = null; - this.guestHomeNodes = null; - this.guestHomeRootNodes = null; - - resetSelectedNode(); - } - - /** - * Determines whether the given NodeRef can be added to the tree as - * a child for example, if it's a folder. - * - * @param nodeRef The NodeRef to check - * @return true if the node should be added to the tree - */ - protected boolean isAddableChild(NodeRef nodeRef) - { - boolean addable = false; - - if (this.getNodeService().exists(nodeRef)) - { - // find it's type so we can see if it's a node we are interested in - QName type = this.getNodeService().getType(nodeRef); - - // make sure the type is defined in the data dictionary - TypeDefinition typeDef = this.getDictionaryService().getType(type); - - if (typeDef != null) - { - // look for folder node types - if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_FOLDER) == true && - this.getDictionaryService().isSubClass(type, ContentModel.TYPE_SYSTEM_FOLDER) == false) - { - addable = true; - } - } - } - - return addable; - } - - /** - * Creates a TreeNode object from the given NodeRef - * - * @param nodeRef The NodeRef to create the TreeNode from - */ - protected TreeNode createTreeNode(NodeRef nodeRef) - { - TreeNode node = new TreeNode(nodeRef.toString(), - Repository.getNameForNode(this.getInternalNodeService(), nodeRef), - (String)this.getInternalNodeService().getProperty(nodeRef, ApplicationModel.PROP_ICON)); - - return node; - } - - /** - * Retrieves the instance of the NavigationBean being used by the application - * - * @return NavigationBean instance - */ - protected NavigationBean getNavigationBean() - { - return (NavigationBean)FacesHelper.getManagedBean( - FacesContext.getCurrentInstance(), NavigationBean.BEAN_NAME); - } - - /** - * Retrieves the instance of the BrowseBean being used by the application - * - * @return BrowseBean instance - */ - protected BrowseBean getBrowseBean() - { - return (BrowseBean)FacesHelper.getManagedBean( - FacesContext.getCurrentInstance(), BrowseBean.BEAN_NAME); - } - - /** - * Returns the map of tree nodes for the given area - * - * @param area The area to retrieve the map for - * @return The map of nodes - */ - protected Map getNodesMapForArea(String area) - { - Map nodes = null; - - if (NavigationBean.LOCATION_COMPANY.equals(area)) - { - nodes = this.companyHomeNodes; - } - else if (NavigationBean.LOCATION_HOME.equals(area)) - { - nodes = this.myHomeNodes; - } - else if (NavigationBean.LOCATION_GUEST.equals(area)) - { - nodes = this.guestHomeNodes; - } - - return nodes; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/ajax/NodeInfoBean.java b/war/src/main/java/org/alfresco/web/bean/ajax/NodeInfoBean.java deleted file mode 100644 index 3c728dc0cf..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/ajax/NodeInfoBean.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.ajax; - -import java.io.IOException; -import java.io.Serializable; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; - -import org.springframework.extensions.surf.util.I18NUtil; -import org.alfresco.repo.content.transform.TransformerInfoException; -import org.alfresco.repo.template.I18NMessageMethod; -import org.alfresco.repo.template.TemplateNode; -import org.alfresco.repo.web.scripts.FileTypeImageUtils; -import org.alfresco.service.cmr.repository.ContentIOException; -import org.alfresco.service.cmr.repository.FileTypeImageSize; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.repository.TemplateException; -import org.alfresco.service.cmr.repository.TemplateImageResolver; -import org.alfresco.web.app.servlet.BaseTemplateContentServlet; -import org.alfresco.web.bean.repository.Repository; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean used by an AJAX control to send information back on the - * requested node. - * - * @author gavinc - */ -public class NodeInfoBean implements Serializable -{ - private static final long serialVersionUID = 137294178658919187L; - - transient private NodeService nodeService; - - private static final Log logger = LogFactory.getLog(NodeInfoBean.class); - - /** - * Returns information on the node identified by the 'noderef' - * parameter found in the ExternalContext. If no noderef is supplied, then the template - * is executed without context. - *

- * The result is the formatted HTML to show on the client. - */ - public void sendNodeInfo() throws IOException - { - FacesContext context = FacesContext.getCurrentInstance(); - ResponseWriter out = context.getResponseWriter(); - - Map requestMap = context.getExternalContext().getRequestParameterMap(); - String strNodeRef = (String)requestMap.get("noderef"); - String strTemplate = (String)requestMap.get("template"); - if (strTemplate == null || strTemplate.length() == 0) - { - strTemplate = "node_summary_panel.ftl"; - } - - NodeRef nodeRef = null; - if (strNodeRef != null && strNodeRef.length() != 0) - { - nodeRef = new NodeRef(strNodeRef); - if (this.getNodeService().exists(nodeRef) == false) - { - out.write("Node could not be found in the repository!"); - return; - } - } - try - { - Repository.getServiceRegistry(context).getTemplateService().processTemplate( - "/alfresco/templates/client/" + strTemplate, getModel(nodeRef, requestMap), out); - } - catch (TemplateException ex) - { - // Try to catch TransformerInfoException to display it in NodeInfo pane. - // Fix bug reported in https://issues.alfresco.com/jira/browse/ETWOTWO-440 - Throwable cause = ex.getCause(); - while (cause != null) - { - cause = cause.getCause(); - if (cause instanceof TransformerInfoException) - { - out.write("" + cause.getMessage() + ""); - return; - } - } - - throw ex; - } - } - - - // ------------------------------------------------------------------------------ - // Bean getters and setters - - /** - * @param nodeService The NodeService to set. - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - private NodeService getNodeService() - { - if (nodeService == null) - { - nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - } - return nodeService; - } - - - // ------------------------------------------------------------------------------ - // Helper methods - - private Map getModel(NodeRef nodeRef, Map requestMap) throws ContentIOException - { - FacesContext context = FacesContext.getCurrentInstance(); - Map model = new HashMap(8, 1.0f); - - I18NUtil.registerResourceBundle("alfresco.messages.webclient"); - // create api methods - model.put("date", new Date()); - model.put("msg", new I18NMessageMethod()); - model.put("url", new BaseTemplateContentServlet.URLHelper(context)); - model.put("locale", I18NUtil.getLocale()); - if (nodeRef != null) - { - model.put("node", new TemplateNode( - nodeRef, - Repository.getServiceRegistry(context), - this.imageResolver)); - } - - // add URL arguments as a map called 'args' to the root of the model - Map args = new HashMap(4, 1.0f); - for (String name : requestMap.keySet()) - { - args.put(name, requestMap.get(name)); - } - model.put("args", args); - - return model; - } - - /** Template Image resolver helper */ - private TemplateImageResolver imageResolver = new TemplateImageResolver() - { - public String resolveImagePathForName(String filename, FileTypeImageSize size) - { - return FileTypeImageUtils.getFileTypeImage(FacesContext.getCurrentInstance(), filename, size); - } - }; - -} diff --git a/war/src/main/java/org/alfresco/web/bean/ajax/PickerBean.java b/war/src/main/java/org/alfresco/web/bean/ajax/PickerBean.java deleted file mode 100644 index 813444025f..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/ajax/PickerBean.java +++ /dev/null @@ -1,563 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.ajax; - -import java.io.Serializable; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.StringTokenizer; - -import javax.faces.context.FacesContext; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.repo.web.scripts.FileTypeImageUtils; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.model.FileFolderService; -import org.alfresco.service.cmr.model.FileInfo; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.ContentReader; -import org.alfresco.service.cmr.repository.ContentService; -import org.alfresco.service.cmr.repository.FileTypeImageSize; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.search.CategoryService; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.servlet.DownloadContentServlet; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.app.servlet.ajax.InvokeCommand; -import org.alfresco.web.bean.BrowseBean; -import org.alfresco.web.bean.repository.Repository; -import org.springframework.extensions.webscripts.json.JSONWriter; -import org.alfresco.web.ui.common.Utils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean backing the ajax requests for the ajax based picker components. - * - * @author Kevin Roast - */ -public class PickerBean implements Serializable -{ - private static final long serialVersionUID = 8950457520023294902L; - - private static final String MSG_CATEGORIES = "categories"; - private static final String MSG_TAGS = "tags"; - private static final String ID_URL = "url"; - private static final String ID_ICON = "icon"; - private static final String ID_CHILDREN = "children"; - private static final String ID_SELECTABLE = "selectable"; - private static final String ID_ISROOT = "isroot"; - private static final String ID_NAME = "name"; - private static final String ID_ID = "id"; - private static final String ID_PARENT = "parent"; - private static final String PARAM_PARENT = "parent"; - private static final String PARAM_CHILD = "child"; - private static final String PARAM_MIMETYPES = "mimetypes"; - - private static final String FOLDER_IMAGE_PREFIX = "/images/icons/"; - - private static Log logger = LogFactory.getLog(PickerBean.class); - - transient private CategoryService categoryService; - transient private NodeService nodeService; - transient private NodeService internalNodeService; - transient private FileFolderService fileFolderService; - - - /** - * @param categoryService The categoryService to set - */ - public void setCategoryService(CategoryService categoryService) - { - this.categoryService = categoryService; - } - - /** - * @return the categoryService - */ - private CategoryService getCategoryService() - { - //check for null in cluster environment - if(categoryService == null) - { - categoryService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getCategoryService(); - } - return categoryService; - } - - /** - * @param nodeService The nodeService to set - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - /** - * @return the nodeService - */ - private NodeService getNodeService() - { - //check for null in cluster environment - if (nodeService == null) - { - nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - } - return nodeService; - } - - /** - * @param internalNodeService The internalNodeService to set. - */ - public void setInternalNodeService(NodeService internalNodeService) - { - this.internalNodeService = internalNodeService; - } - - /** - * @return the internalNodeService - */ - private NodeService getInternalNodeService() - { - //check for null in cluster environment - if (internalNodeService == null) - { - internalNodeService = (NodeService) FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), "nodeService"); - } - return internalNodeService; - } - - /** - * @param fileFolderService the FileFolderService to set - */ - public void setFileFolderService(FileFolderService fileFolderService) - { - this.fileFolderService = fileFolderService; - } - - /** - * @return the fileFolderService - */ - private FileFolderService getFileFolderService() - { - if (fileFolderService == null) - { - fileFolderService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getFileFolderService(); - } - return fileFolderService; - } - - /** - * Return the JSON objects representing a list of categories. - * - * IN: "parent" - null for root categories, else the parent noderef of the categories to retrieve. - * - * The pseudo root node 'Categories' is not selectable. - */ - @InvokeCommand.ResponseMimetype(value=MimetypeMap.MIMETYPE_HTML) - public void getCategoryNodes() throws Exception - { - FacesContext fc = FacesContext.getCurrentInstance(); - - UserTransaction tx = null; - try - { - tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true); - tx.begin(); - - Collection childRefs; - NodeRef parentRef = null; - Map params = fc.getExternalContext().getRequestParameterMap(); - String strParentRef = Utils.encode((String)params.get(PARAM_PARENT)); - if (strParentRef == null || strParentRef.length() == 0) - { - childRefs = this.getCategoryService().getRootCategories( - Repository.getStoreRef(), - ContentModel.ASPECT_GEN_CLASSIFIABLE); - } - else - { - parentRef = new NodeRef(strParentRef); - childRefs = this.getCategoryService().getChildren( - parentRef, - CategoryService.Mode.SUB_CATEGORIES, - CategoryService.Depth.IMMEDIATE); - } - - JSONWriter out = new JSONWriter(fc.getResponseWriter()); - out.startObject(); - out.startValue(ID_PARENT); - out.startObject(); - if (parentRef == null) - { - out.writeNullValue(ID_ID); - out.writeValue(ID_NAME, Application.getMessage(fc, MSG_CATEGORIES)); - out.writeValue(ID_ISROOT, true); - out.writeValue(ID_SELECTABLE, false); - } - else - { - out.writeValue(ID_ID, strParentRef); - out.writeValue(ID_NAME, Repository.getNameForNode(this.getInternalNodeService(), parentRef)); - } - out.endObject(); - out.endValue(); - out.startValue(ID_CHILDREN); - out.startArray(); - for (ChildAssociationRef ref : childRefs) - { - NodeRef nodeRef = ref.getChildRef(); - out.startObject(); - out.writeValue(ID_ID, nodeRef.toString()); - out.writeValue(ID_NAME, Repository.getNameForNode(this.getInternalNodeService(), nodeRef)); - out.endObject(); - } - out.endArray(); - out.endValue(); - out.endObject(); - - tx.commit(); - } - catch (Throwable err) - { - Utils.addErrorMessage("PickerBean exception in getCategoryRootNodes()", err); - fc.getResponseWriter().write("ERROR: " + err.getMessage()); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - } - - /** - * Return the JSON objects representing a list of cm:folder nodes. - * - * IN: "parent" - noderef (can be null) of the parent to retrieve the child folder nodes for. Null is valid - * and specifies the Company Home root as the parent. - * IN: "child" - non-null value of the child noderef to retrieve the siblings for - the parent value returned - * in the JSON response will be the parent of the specified child. - * - * The 16x16 pixel folder icon path is output as the 'icon' property for each child folder. - */ - @InvokeCommand.ResponseMimetype(value=MimetypeMap.MIMETYPE_HTML) - public void getTagNodes() throws Exception - { - FacesContext fc = FacesContext.getCurrentInstance(); - - UserTransaction tx = null; - try - { - tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true); - tx.begin(); - - Collection childRefs; - NodeRef parentRef = null; - Map params = fc.getExternalContext().getRequestParameterMap(); - String strParentRef = Utils.encode((String)params.get(ID_PARENT)); - if (strParentRef == null || strParentRef.length() == 0) - { - childRefs = this.getCategoryService().getRootCategories( - Repository.getStoreRef(), - ContentModel.ASPECT_TAGGABLE); - } - else - { - parentRef = new NodeRef(strParentRef); - childRefs = this.getCategoryService().getChildren( - parentRef, - CategoryService.Mode.SUB_CATEGORIES, - CategoryService.Depth.IMMEDIATE); - } - - JSONWriter out = new JSONWriter(fc.getResponseWriter()); - out.startObject(); - out.startValue(ID_PARENT); - out.startObject(); - if (parentRef == null) - { - out.writeNullValue(ID_ID); - out.writeValue(ID_NAME, Application.getMessage(fc, MSG_TAGS)); - out.writeValue(ID_ISROOT, true); - out.writeValue(ID_SELECTABLE, false); - } - else - { - out.writeValue(ID_ID, strParentRef); - out.writeValue(ID_NAME, Repository.getNameForNode(this.getInternalNodeService(), parentRef)); - } - out.endObject(); - out.endValue(); - out.startValue(ID_CHILDREN); - out.startArray(); - for (ChildAssociationRef ref : childRefs) - { - NodeRef nodeRef = ref.getChildRef(); - out.startObject(); - out.writeValue(ID_ID, nodeRef.toString()); - out.writeValue(ID_NAME, Repository.getNameForNode(this.getInternalNodeService(), nodeRef)); - out.endObject(); - } - out.endArray(); - out.endValue(); - out.endObject(); - - tx.commit(); - } - catch (Throwable err) - { - Utils.addErrorMessage("PickerBean exception in getTagNodes()", err); - fc.getResponseWriter().write("ERROR: " + err.getMessage()); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - } - - @InvokeCommand.ResponseMimetype(value=MimetypeMap.MIMETYPE_HTML) - public void getFolderNodes() throws Exception - { - FacesContext fc = FacesContext.getCurrentInstance(); - - UserTransaction tx = null; - try - { - tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true); - tx.begin(); - - List childRefs; - NodeRef companyHomeRef = new NodeRef(Repository.getStoreRef(), Application.getCompanyRootId(fc)); - - NodeRef parentRef = null; - Map params = fc.getExternalContext().getRequestParameterMap(); - String strChildRef = Utils.encode((String)params.get(PARAM_CHILD)); - if (strChildRef != null && strChildRef.length() != 0) - { - // TODO: check permission on the parent - NodeRef childRef = new NodeRef(strChildRef); - parentRef = this.getNodeService().getPrimaryParent(childRef).getParentRef(); - } - else - { - // TODO: check permission on the parent - String strParentRef = Utils.encode((String)params.get(PARAM_PARENT)); - if (strParentRef == null || strParentRef.length() == 0) - { - parentRef = companyHomeRef; - strParentRef = parentRef.toString(); - } - else - { - parentRef = new NodeRef(strParentRef); - } - } - - List folders = this.getFileFolderService().listFolders(parentRef); - - JSONWriter out = new JSONWriter(fc.getResponseWriter()); - out.startObject(); - out.startValue(ID_PARENT); - out.startObject(); - out.writeValue(ID_ID, parentRef.toString()); - out.writeValue(ID_NAME, Repository.getNameForNode(this.getInternalNodeService(), parentRef)); - if (parentRef.equals(companyHomeRef)) - { - out.writeValue(ID_ISROOT, true); - } - out.endObject(); - out.endValue(); - out.startValue(ID_CHILDREN); - out.startArray(); - - // filter out those children that are not spaces - for (FileInfo folder : folders) - { - out.startObject(); - out.writeValue(ID_ID, folder.getNodeRef().toString()); - out.writeValue(ID_NAME, (String)folder.getProperties().get(ContentModel.PROP_NAME)); - String icon = (String)folder.getProperties().get(ApplicationModel.PROP_ICON); - out.writeValue(ID_ICON, FOLDER_IMAGE_PREFIX + (icon != null ? icon + "-16.gif" : BrowseBean.SPACE_SMALL_DEFAULT + ".gif")); - out.endObject(); - } - - out.endArray(); - out.endValue(); - out.endObject(); - - tx.commit(); - } - catch (Throwable err) - { - Utils.addErrorMessage("PickerBean exception in getFolderNodes()", err); - fc.getResponseWriter().write("ERROR: " + err.getMessage()); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - } - - /** - * Return the JSON objects representing a list of cm:folder and cm:content nodes. - * - * IN: "parent" - noderef (can be null) of the parent to retrieve the child nodes for. Null is valid - * and specifies the Company Home root as the parent. - * IN: "child" - non-null value of the child noderef to retrieve the siblings for - the parent value returned - * in the JSON response will be the parent of the specified child. - * IN: "mimetypes" (optional) - if set, a comma separated list of mimetypes to restrict the file list. - * - * It is assumed that only files should be selectable, all cm:folder nodes will be marked with the - * 'selectable:false' property. Therefore the parent (which is a folder) is not selectable. - * - * The 16x16 pixel node icon path is output as the 'icon' property for each child, in addition each - * cm:content node has an property of 'url' for content download. - */ - @InvokeCommand.ResponseMimetype(value=MimetypeMap.MIMETYPE_HTML) - public void getFileFolderNodes() throws Exception - { - FacesContext fc = FacesContext.getCurrentInstance(); - - UserTransaction tx = null; - try - { - tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true); - tx.begin(); - - DictionaryService dd = Repository.getServiceRegistry(fc).getDictionaryService(); - ContentService cs = Repository.getServiceRegistry(fc).getContentService(); - - List childRefs; - NodeRef companyHomeRef = new NodeRef(Repository.getStoreRef(), Application.getCompanyRootId(fc)); - - NodeRef parentRef = null; - Map params = fc.getExternalContext().getRequestParameterMap(); - String strChildRef = Utils.encode((String)params.get(PARAM_CHILD)); - if (strChildRef != null && strChildRef.length() != 0) - { - // TODO: check permission on the parent - NodeRef childRef = new NodeRef(strChildRef); - parentRef = this.getNodeService().getPrimaryParent(childRef).getParentRef(); - } - else - { - // TODO: check permission on the parent - String strParentRef = Utils.encode((String)params.get(PARAM_PARENT)); - if (strParentRef == null || strParentRef.length() == 0) - { - parentRef = companyHomeRef; - strParentRef = parentRef.toString(); - } - else - { - parentRef = new NodeRef(strParentRef); - } - } - - // look for mimetype restriction parameter - Set mimetypes = null; - String mimetypeParam = (String)params.get(PARAM_MIMETYPES); - if (mimetypeParam != null && mimetypeParam.length() != 0) - { - // convert to a set of mimetypes to test each file against - mimetypes = new HashSet(); - for (StringTokenizer t = new StringTokenizer(mimetypeParam, ","); t.hasMoreTokens(); /**/) - { - mimetypes.add(t.nextToken()); - } - } - - List items = this.getFileFolderService().list(parentRef); - - JSONWriter out = new JSONWriter(fc.getResponseWriter()); - out.startObject(); - out.startValue(ID_PARENT); - out.startObject(); - out.writeValue(ID_ID, parentRef.toString()); - out.writeValue(ID_NAME, Repository.getNameForNode(this.getInternalNodeService(), parentRef)); - if (parentRef.equals(companyHomeRef)) - { - out.writeValue(ID_ISROOT, true); - } - out.writeValue(ID_SELECTABLE, false); - out.endObject(); - out.endValue(); - out.startValue(ID_CHILDREN); - out.startArray(); - - for (FileInfo item : items) - { - if (dd.isSubClass(this.getInternalNodeService().getType(item.getNodeRef()), ContentModel.TYPE_FOLDER)) - { - // found a folder - out.startObject(); - out.writeValue(ID_ID, item.getNodeRef().toString()); - String name = (String)item.getProperties().get(ContentModel.PROP_NAME); - out.writeValue(ID_NAME, name); - String icon = (String)item.getProperties().get(ApplicationModel.PROP_ICON); - out.writeValue(ID_ICON, FOLDER_IMAGE_PREFIX + (icon != null ? icon + "-16.gif" : BrowseBean.SPACE_SMALL_DEFAULT + ".gif")); - out.writeValue(ID_SELECTABLE, false); - out.endObject(); - } - else - { - // must be a file - boolean validFile = true; - if (mimetypes != null) - { - validFile = false; - ContentReader reader = cs.getReader(item.getNodeRef(), ContentModel.PROP_CONTENT); - if (reader != null) - { - String mimetype = reader.getMimetype(); - validFile = (mimetype != null && mimetypes.contains(mimetype)); - } - } - if (validFile) - { - out.startObject(); - out.writeValue(ID_ID, item.getNodeRef().toString()); - String name = (String)item.getProperties().get(ContentModel.PROP_NAME); - out.writeValue(ID_NAME, name); - String icon = FileTypeImageUtils.getFileTypeImage(fc, name, FileTypeImageSize.Small); - out.writeValue(ID_ICON, icon); - out.writeValue(ID_URL, DownloadContentServlet.generateBrowserURL(item.getNodeRef(), name)); - out.endObject(); - } - } - } - - out.endArray(); - out.endValue(); - out.endObject(); - - tx.commit(); - } - catch (Throwable err) - { - Utils.addErrorMessage("PickerBean exception in getFileFolderNodes()", err); - fc.getResponseWriter().write("ERROR: " + err.getMessage()); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/bean/ajax/PortletActionsBean.java b/war/src/main/java/org/alfresco/web/bean/ajax/PortletActionsBean.java deleted file mode 100644 index 767ea5c6fe..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/ajax/PortletActionsBean.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.ajax; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; - -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.repo.version.VersionModel; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.version.Version; -import org.alfresco.service.cmr.version.VersionType; -import org.alfresco.web.app.servlet.ajax.InvokeCommand; -import org.alfresco.web.bean.repository.Repository; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean backing the ajax requests from various Portlet webscripts. - * - * @author Mike Hatfield - */ -public class PortletActionsBean implements Serializable -{ - private static final long serialVersionUID = -8230154592621310289L; - - private static Log logger = LogFactory.getLog(PortletActionsBean.class); - - @InvokeCommand.ResponseMimetype(value=MimetypeMap.MIMETYPE_HTML) - public void deleteItem() throws Exception - { - FacesContext fc = FacesContext.getCurrentInstance(); - ResponseWriter out = fc.getResponseWriter(); - - Map requestMap = fc.getExternalContext().getRequestParameterMap(); - String strNodeRef = (String)requestMap.get("noderef"); - if (strNodeRef != null && strNodeRef.length() != 0) - { - try - { - Repository.getServiceRegistry(fc).getFileFolderService().delete(new NodeRef(strNodeRef)); - out.write("OK: " + strNodeRef); - } - catch (Throwable err) - { - out.write("ERROR: " + err.getMessage()); - } - } - } - - @InvokeCommand.ResponseMimetype(value=MimetypeMap.MIMETYPE_HTML) - public void checkoutItem() throws Exception - { - FacesContext fc = FacesContext.getCurrentInstance(); - ResponseWriter out = fc.getResponseWriter(); - - Map requestMap = fc.getExternalContext().getRequestParameterMap(); - String strNodeRef = (String)requestMap.get("noderef"); - if (strNodeRef != null && strNodeRef.length() != 0) - { - try - { - Repository.getServiceRegistry(fc).getCheckOutCheckInService().checkout(new NodeRef(strNodeRef)); - out.write("OK: " + strNodeRef); - } - catch (Throwable err) - { - out.write("ERROR: " + err.getMessage()); - } - } - } - - @InvokeCommand.ResponseMimetype(value=MimetypeMap.MIMETYPE_HTML) - public void checkinItem() throws Exception - { - FacesContext fc = FacesContext.getCurrentInstance(); - ResponseWriter out = fc.getResponseWriter(); - - Map requestMap = fc.getExternalContext().getRequestParameterMap(); - String strNodeRef = (String)requestMap.get("noderef"); - if (strNodeRef != null && strNodeRef.length() != 0) - { - try - { - Map props = new HashMap(2, 1.0f); - props.put(Version.PROP_DESCRIPTION, ""); - props.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR); - Repository.getServiceRegistry(fc).getCheckOutCheckInService().checkin(new NodeRef(strNodeRef), props); - out.write("OK: " + strNodeRef); - } - catch (Throwable err) - { - out.write("ERROR: " + err.getMessage()); - } - } - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/bean/ajax/PresenceProxyBean.java b/war/src/main/java/org/alfresco/web/bean/ajax/PresenceProxyBean.java deleted file mode 100644 index 0ac3072c15..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/ajax/PresenceProxyBean.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.ajax; - -import java.io.IOException; -import java.io.Serializable; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; - -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.web.app.servlet.ajax.InvokeCommand; -import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpMethod; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.params.HttpMethodParams; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean which proxies requests to online presence servers. - * - * @author Mike Hatfield - */ -public class PresenceProxyBean implements Serializable -{ - private static final long serialVersionUID = -3041576848188629589L; - - private static Log logger = LogFactory.getLog(PresenceProxyBean.class); - - @InvokeCommand.ResponseMimetype(value=MimetypeMap.MIMETYPE_HTML) - public void proxyRequest() throws Exception - { - FacesContext fc = FacesContext.getCurrentInstance(); - ResponseWriter out = fc.getResponseWriter(); - - Map requestMap = fc.getExternalContext().getRequestParameterMap(); - String url = (String)requestMap.get("url"); - - if (logger.isDebugEnabled()) - logger.debug("PresenceProxyBean.proxyRequest() url=" + url); - - if (url != null) - { - String response = getUrlResponse(url); - out.write(response); - } - } - - /** - * Perform request - */ - public String getUrlResponse(String requestUrl) - { - String response = ""; - HttpClient client = new HttpClient(); - HttpMethod method = new GetMethod(requestUrl); - method.setRequestHeader("Accept", "*/*"); - client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); - try - { - int statusCode = client.executeMethod(method); - if (statusCode == HttpStatus.SC_OK) - { - response = method.getResponseBodyAsString(); - } - else - { - response = method.getStatusText(); - } - } - catch (HttpException e) - { - response = e.getMessage(); - } - catch (IOException e) - { - response = e.getMessage(); - } - finally - { - // Release the connection. - method.releaseConnection(); - } - - return response; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/ajax/TaskInfoBean.java b/war/src/main/java/org/alfresco/web/bean/ajax/TaskInfoBean.java deleted file mode 100644 index 6954914776..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/ajax/TaskInfoBean.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.ajax; - -import java.io.IOException; -import java.io.Serializable; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; - -import org.alfresco.repo.template.I18NMessageMethod; -import org.alfresco.repo.template.Workflow; -import org.alfresco.repo.web.scripts.FileTypeImageUtils; -import org.alfresco.service.cmr.repository.FileTypeImageSize; -import org.alfresco.service.cmr.repository.TemplateImageResolver; -import org.alfresco.service.cmr.workflow.WorkflowService; -import org.alfresco.service.cmr.workflow.WorkflowTask; -import org.alfresco.web.app.servlet.BaseTemplateContentServlet; -import org.alfresco.web.bean.repository.Repository; -import org.springframework.extensions.surf.util.I18NUtil; - -/** - * Bean used by an AJAX control to send information back on the requested workflow task. - * - * @author Kevin Roast - */ -public class TaskInfoBean implements Serializable -{ - private static final long serialVersionUID = -6627537519541525897L; - - transient private WorkflowService workflowService; - - /** - * Returns information for the workflow task identified by the 'taskId' - * parameter found in the ExternalContext. - *

- * The result is the formatted HTML to show on the client. - */ - public void sendTaskInfo() throws IOException - { - FacesContext context = FacesContext.getCurrentInstance(); - ResponseWriter out = context.getResponseWriter(); - - String taskId = (String)context.getExternalContext().getRequestParameterMap().get("taskId"); - if (taskId == null || taskId.length() == 0) - { - throw new IllegalArgumentException("'taskId' parameter is missing"); - } - - WorkflowTask task = this.getWorkflowService().getTaskById(taskId); - if (task != null) - { - Repository.getServiceRegistry(context).getTemplateService().processTemplate( - "/alfresco/templates/client/task_summary_panel.ftl", getModel(task), out); - } - else - { - out.write("Task could not be found."); - } - } - - /** - * Returns the resource list for the workflow task identified by the 'taskId' - * parameter found in the ExternalContext. - *

- * The result is the formatted HTML to show on the client. - */ - public void sendTaskResources() throws IOException - { - FacesContext context = FacesContext.getCurrentInstance(); - ResponseWriter out = context.getResponseWriter(); - - String taskId = (String)context.getExternalContext().getRequestParameterMap().get("taskId"); - if (taskId == null || taskId.length() == 0) - { - throw new IllegalArgumentException("'taskId' parameter is missing"); - } - - WorkflowTask task = this.getWorkflowService().getTaskById(taskId); - if (task != null) - { - Repository.getServiceRegistry(context).getTemplateService().processTemplate( - "/alfresco/templates/client/task_resource_panel.ftl", getModel(task), out); - } - else - { - out.write("Task could not be found."); - } - } - - - // ------------------------------------------------------------------------------ - // Bean getters and setters - - /** - * @param workflowService The WorkflowService to set. - */ - public void setWorkflowService(WorkflowService workflowService) - { - this.workflowService = workflowService; - } - - private WorkflowService getWorkflowService() - { - if (workflowService == null) - { - workflowService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getWorkflowService(); - } - return workflowService; - } - - - // ------------------------------------------------------------------------------ - // Helper methods - - private Map getModel(WorkflowTask task) - { - FacesContext context = FacesContext.getCurrentInstance(); - Map model = new HashMap(8, 1.0f); - - I18NUtil.registerResourceBundle("alfresco.messages.webclient"); - // create template api methods and objects - model.put("date", new Date()); - model.put("msg", new I18NMessageMethod()); - model.put("url", new BaseTemplateContentServlet.URLHelper(context)); - model.put("locale", I18NUtil.getLocale()); - model.put("task", new Workflow.WorkflowTaskItem( - Repository.getServiceRegistry(context), - this.imageResolver, - task)); - - return model; - } - - /** Template Image resolver helper */ - private TemplateImageResolver imageResolver = new TemplateImageResolver() - { - public String resolveImagePathForName(String filename, FileTypeImageSize size) - { - return FileTypeImageUtils.getFileTypeImage(FacesContext.getCurrentInstance(), filename, size); - } - }; -} diff --git a/war/src/main/java/org/alfresco/web/bean/categories/CategoriesDialog.java b/war/src/main/java/org/alfresco/web/bean/categories/CategoriesDialog.java deleted file mode 100644 index 1b57a77254..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/categories/CategoriesDialog.java +++ /dev/null @@ -1,705 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.categories; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.search.CategoryService; -import org.alfresco.service.cmr.search.CategoryService.Depth; -import org.alfresco.service.cmr.search.CategoryService.Mode; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.IContextListener; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.dialog.ChangeViewSupport; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.IBreadcrumbHandler; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.alfresco.web.ui.common.component.UIBreadcrumb; -import org.alfresco.web.ui.common.component.UIListItem; -import org.alfresco.web.ui.common.component.UIModeList; -import org.alfresco.web.ui.common.component.data.UIRichList; -import org.alfresco.web.ui.repo.component.IRepoBreadcrumbHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Backing Bean for the Category Management pages. - * - * @author Kevin Roast - */ -public class CategoriesDialog extends BaseDialogBean implements IContextListener, ChangeViewSupport -{ - private static final long serialVersionUID = -1254971127977205987L; - - public static final String KEY_CATEGORY = "category"; - public static final String KEY_CATEGORY_FLAG = "categoryFlag"; - - public static final String PARAM_CATEGORY_REF = "categoryRef"; - - public static final String CATEGORIES_DIALOG_CLASS_NAME = "org.alfresco.web.bean.categories.CategoriesDialog"; - - private static final String VIEW_ICONS = "icons"; - private static final String VIEW_DETAILS = "details"; - - private static final String LABEL_VIEW_ICONS = "category_icons"; - private static final String LABEL_VIEW_DETAILS = "category_details"; - private final static String MSG_CLOSE = "close"; - - transient private CategoryService categoryService; - - /** Members of the linked items of a category */ - private Collection members = null; - - /** Currently visible category Node */ - private Node category = null; - - /** Current category ref */ - private NodeRef categoryRef = null; - - /** Action category node */ - private Node actionCategory = null; - - /** RichList view mode */ - private String viewMode = "icons"; - - /** Component references */ - protected UIRichList categoriesRichList; - - /** Category path breadcrumb location */ - private List location = null; - - private static final String MSG_CATEGORIES = "categories"; - - /** Dialog properties */ - private String name = null; - private String description = null; - - private static Log logger = LogFactory.getLog(CategoriesDialog.class); - - // ------------------------------------------------------------------------------ - // Construction - - /** - * Default Constructor - */ - public CategoriesDialog() - { - UIContextService.getInstance(FacesContext.getCurrentInstance()).registerBean(this); - } - - // ------------------------------------------------------------------------------ - - /** - * @return Returns the members count for current action category. - */ - public int getMembersCount() - { - return (getMembers() != null ? getMembers().size() : 0); - } - - public Collection getMembers() - { - return members; - } - - public void setMembers(Collection members) - { - this.members = members; - } - - public Node getActionCategory() - { - return actionCategory; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name; - } - - public String getId() - { - return getCurrentCategoryId(); - } - - public String getDescription() - { - return description; - } - - public void setDescription(String description) - { - this.description = description; - } - - public CategoryService getCategoryService() - { - if (categoryService == null) - { - categoryService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getCategoryService(); - } - - return categoryService; - } - - public void setCategoryService(CategoryService categoryService) - { - this.categoryService = categoryService; - } - - public Node getCategory() - { - return category; - } - - public void setCategory(Node category) - { - this.category = category; - } - - public NodeRef getCategoryRef() - { - return categoryRef; - } - - public void setCategoryRef(NodeRef categoryRef) - { - this.categoryRef = categoryRef; - } - - public UIRichList getCategoriesRichList() - { - return categoriesRichList; - } - - public void setCategoriesRichList(UIRichList categoriesRichList) - { - this.categoriesRichList = categoriesRichList; - } - - @Override - public Object getActionsContext() - { - return this; - } - - /** - * @param node Set the Node to be used for the current category screen action. - */ - @SuppressWarnings("unchecked") - public void setActionCategory(Node node) - { - this.actionCategory = node; - - if (node != null) - { - // setup form properties - setName(node.getName()); - setDescription((String)node.getProperties().get(ContentModel.PROP_DESCRIPTION)); - setMembers(getCategoryService().getChildren(node.getNodeRef(), Mode.MEMBERS, Depth.ANY)); - } - else - { - setName(null); - setDescription(null); - Object emptyCollection = Collections.emptyList(); - setMembers((Collection) emptyCollection); - } - } - - /** - * @return The currently displayed category as a Node or null if at the root. - */ - public Node getCurrentCategory() - { - if (getCategory() == null) - { - if (getCategoryRef() != null) - { - setCategory(new Node(getCategoryRef())); - } - } - - return getCategory(); - } - - /** - * @return The ID of the currently displayed category or null if at the root. - */ - public String getCurrentCategoryId() - { - if (getCategoryRef() != null) - { - return getCategoryRef().getId(); - } - else - { - return null; - } - } - - /** - * Set the current category node. - *

- * Setting this value causes the UI to update and display the specified node as current. - * - * @param ref The current category node. - */ - public void setCurrentCategory(NodeRef ref) - { - if (logger.isDebugEnabled()) - logger.debug("Setting current category: " + ref); - - // set the current NodeRef for our UI context operations - setCategoryRef(ref); - - // clear current node context - setCategory(null); - - // inform that the UI needs updating after this change - contextUpdated(); - } - - public void setLocation(List location) - { - this.location = location; - } - - /** - * @return Breadcrumb location list - */ - public List getLocation() - { - if (this.location == null) - { - List loc = new ArrayList(8); - loc.add(new CategoryBreadcrumbHandler(null, - Application.getMessage(FacesContext.getCurrentInstance(), MSG_CATEGORIES))); - - setLocation(loc); - } - return this.location; - } - - /** - * @return The list of categories Nodes to display. Returns the list root categories or the - * list of sub-categories for the current category if set. - */ - public List getCategories() - { - List categories; - - UserTransaction tx = null; - try - { - FacesContext context = FacesContext.getCurrentInstance(); - tx = Repository.getUserTransaction(context, true); - tx.begin(); - - Collection refs; - if (getCategoryRef() == null) - { - // root categories - refs = getCategoryService().getCategories(Repository.getStoreRef(), ContentModel.ASPECT_GEN_CLASSIFIABLE, Depth.IMMEDIATE); - } - else - { - // sub-categories of an existing category - refs = getCategoryService().getChildren(getCategoryRef(), Mode.SUB_CATEGORIES, Depth.IMMEDIATE); - } - categories = new ArrayList(refs.size()); - for (ChildAssociationRef child : refs) - { - Node categoryNode = new Node(child.getChildRef()); - // force early props init within transaction - categoryNode.getProperties(); - categories.add(categoryNode); - } - - // commit the transaction - tx.commit(); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {refErr.getNodeRef()})); - categories = Collections.emptyList(); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err); - categories = Collections.emptyList(); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - - return categories; - } - - /** - * Set the Category to be used for next action dialog - */ - public void setupCategoryAction(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - if (logger.isDebugEnabled()) - logger.debug("Setup for action, setting current Category to: " + id); - - try - { - // create the node ref, then our node representation - NodeRef ref = new NodeRef(Repository.getStoreRef(), id); - Node node = new Node(ref); - - // prepare a node for the action context - setActionCategory(node); - - // clear datalist cache ready from return from action dialog - contextUpdated(); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {id})); - } - } - } - - /** - * Clear the category action context - e.g. ready for a Create operation - */ - public void clearCategoryAction(ActionEvent event) - { - setActionCategory(null); - - // clear datalist cache ready from return from action dialog - contextUpdated(); - } - - /** - * Reset the current category navigation point - e.g. ready for redisplay of the root UI - */ - public void resetCategoryNavigation(ActionEvent event) - { - setCurrentCategory(null); - this.location = null; - } - - /** - * Action called when a category folder is clicked. - * Navigate into the category. - */ - public void clickCategory(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - try - { - NodeRef ref = new NodeRef(Repository.getStoreRef(), id); - // refresh UI based on node selection - updateUILocation(ref); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] { id })); - } - } - } - - /** - * Update the breadcrumb with the clicked category location - */ - private void updateUILocation(NodeRef ref) - { - String name = Repository.getNameForNode(getNodeService(), ref); - getLocation().add(new CategoryBreadcrumbHandler(ref, name)); - this.setCurrentCategory(ref); - } - - /** - * If category.equals(handler.label) then the breadcrumb reverts one step back
- * (for deleting) - *

- * Else current breadcrumb is updated accordingly to the current category
- * (for editing) - */ - protected void removeFromBreadcrumb(String categoryToRemove, String categoryFlag) - { - // remove this node from the breadcrumb if required - List location = getLocation(); - CategoryBreadcrumbHandler handler = (CategoryBreadcrumbHandler) location.get(location.size() - 1); - - // see if the current breadcrumb location is our Category - if (categoryToRemove.equals(handler.label)) - { - location.remove(location.size() - 1); - - // now work out which Category to set the list to refresh against - if (location.size() != 0) - { - handler = (CategoryBreadcrumbHandler) location.get(location.size() - 1); - this.setCurrentCategory(handler.nodeRef); - } - } - else if (categoryFlag.equals("true")) - { - // We don't need to modify the breadcrumb, as editing/deleting is made through an icon. - // the dialog should get back to the original location. - this.setCurrentCategory(handler.nodeRef); - } - else - { - if (getCategory() != null) - { - handler = new CategoryBreadcrumbHandler( - getCategory().getNodeRef(), Repository.getNameForNode(getNodeService(), getCategory().getNodeRef())); - location.set(location.size() - 1, handler); - this.setCurrentCategory(handler.nodeRef); - } - } - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - public String getContainerSubTitle() - { - if (getCurrentCategoryId() != null) - { - return getCurrentCategory().getName(); - } - - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CATEGORIES); - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } - - // ------------------------------------------------------------------------------ - // IContextListener implementation - - /** - * @see org.alfresco.web.app.context.IContextListener#contextUpdated() - */ - public void contextUpdated() - { - if (logger.isDebugEnabled()) - logger.debug("Invalidating Category Management Components..."); - - // force a requery of the current category ref properties - setCategory(null); - - // force a requery of the richlist dataset - if (this.categoriesRichList != null) - { - this.categoriesRichList.setValue(null); - } - } - - /** - * @see org.alfresco.web.app.context.IContextListener#areaChanged() - */ - public void areaChanged() - { - // nothing to do - } - - /** - * @see org.alfresco.web.app.context.IContextListener#spaceChanged() - */ - public void spaceChanged() - { - // nothing to do - } - - // ------------------------------------------------------------------------------ - // Inner classes - - /** - * Class to handle breadcrumb interaction for Categories pages - */ - public class CategoryBreadcrumbHandler implements IRepoBreadcrumbHandler - { - private static final long serialVersionUID = 3831234653171036630L; - - /** - * Constructor - * - * @param nodeRef The NodeRef for this browse navigation element - * @param label Element label - */ - public CategoryBreadcrumbHandler(NodeRef nodeRef, String label) - { - this.label = label; - this.nodeRef = nodeRef; - } - - /** - * @see java.lang.Object#toString() - */ - public String toString() - { - return this.label; - } - - /** - * @see org.alfresco.web.ui.common.component.IBreadcrumbHandler#navigationOutcome(org.alfresco.web.ui.common.component.UIBreadcrumb) - */ - @SuppressWarnings("unchecked") - public String navigationOutcome(UIBreadcrumb breadcrumb) - { - // All category breadcrumb elements relate to a Categiry Node Id - // when selected we set the current category Id and return - setCurrentCategory(this.nodeRef); - setLocation((List)breadcrumb.getValue()); - - return null; - } - - public NodeRef getNodeRef() - { - return this.nodeRef; - } - - private NodeRef nodeRef; - private String label; - } - - public List getViewItems() - { - FacesContext context = FacesContext.getCurrentInstance(); - List items = new ArrayList(2); - - UIListItem item1 = new UIListItem(); - item1.setValue(VIEW_ICONS); - item1.setLabel(Application.getMessage(context, LABEL_VIEW_ICONS)); - items.add(item1); - - UIListItem item2 = new UIListItem(); - item2.setValue(VIEW_DETAILS); - item2.setLabel(Application.getMessage(context, LABEL_VIEW_DETAILS)); - items.add(item2); - - return items; - } - - @Override - public void restored() - { - Object categoryToRemove = FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get(KEY_CATEGORY); - Object categoryFlag = FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get(KEY_CATEGORY_FLAG); - if (categoryToRemove != null) - { - if (logger.isDebugEnabled()) - logger.debug("Removing group '" + categoryToRemove + "' from breadcrumb"); - if (categoryFlag != null) - { - removeFromBreadcrumb((String)categoryToRemove, (String)categoryFlag); - } - else - { - removeFromBreadcrumb((String)categoryToRemove, Boolean.FALSE.toString()); - } - } - contextUpdated(); - } - - public String getViewMode() - { - return viewMode; - } - - public void setViewMode(String viewMode) - { - this.viewMode = viewMode; - } - - /** - * Change the current view mode based on user selection - * - * @param event ActionEvent - */ - public void viewModeChanged(ActionEvent event) - { - UIModeList viewList = (UIModeList)event.getComponent(); - - // get the view mode ID - setViewMode(viewList.getValue().toString()); - } - - - - @Override - public String getMoreActionsConfigId() - { - if(getCurrentCategoryId() != null) - { - return "category_more_actions"; - } - return null; - } - - public NodeRef getNodeRef() - { - return getCurrentCategory().getNodeRef(); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/categories/CreateCategoryDialog.java b/war/src/main/java/org/alfresco/web/bean/categories/CreateCategoryDialog.java deleted file mode 100644 index 1908f5e1dc..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/categories/CreateCategoryDialog.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.categories; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.HashMap; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.transaction.RetryingTransactionHelper; -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.search.CategoryService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; - -public class CreateCategoryDialog extends BaseDialogBean -{ - private static final long serialVersionUID = 1905920932992642119L; - - private static final String DEFAULT_OUTCOME = "finish"; - - transient protected CategoryService categoryService; - - /** Current category ref */ - private NodeRef categoryRef = null; - - /** Dialog properties */ - private String name = null; - private String description = null; - - @Override - public void init(Map parameters) - { - this.isFinished = false; - - // retrieve parameters - String ref = parameters.get(CategoriesDialog.PARAM_CATEGORY_REF); - - this.name = null; - this.description = null; - - if (ref != null) - { - categoryRef = new NodeRef(ref); - } - else - { - categoryRef = null; - } - } - - /** - * @return the categoryService - */ - private CategoryService getCategoryService() - { - //check for null in cluster environment - if(categoryService == null) - { - categoryService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getCategoryService(); - } - return categoryService; - } - - public void setCategoryService(CategoryService categoryService) - { - this.categoryService = categoryService; - } - - public NodeRef getCategoryRef() - { - return categoryRef; - } - - public void setCategoryRef(NodeRef categoryRef) - { - this.categoryRef = categoryRef; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name; - } - - public String getDescription() - { - return description; - } - - public void setDescription(String description) - { - this.description = description; - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - finishCreate(); - return outcome; - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "new_category"); - } - - public String finishCreate() - { - String outcome = DEFAULT_OUTCOME; - - try - { - FacesContext context = FacesContext.getCurrentInstance(); - RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(context); - RetryingTransactionCallback callback = new RetryingTransactionCallback() - { - public Object execute() throws Throwable - { - // create category using categoryservice - NodeRef ref; - if (getCategoryRef() == null || getCategoryRef().getId().equals("null")) - { - ref = getCategoryService().createRootCategory(Repository.getStoreRef(), ContentModel.ASPECT_GEN_CLASSIFIABLE, getName()); - } - else - { - ref = getCategoryService().createCategory(getCategoryRef(), getName()); - } - - // apply the titled aspect - for description - Map titledProps = new HashMap(1, 1.0f); - titledProps.put(ContentModel.PROP_DESCRIPTION, getDescription()); - getNodeService().addAspect(ref, ContentModel.ASPECT_TITLED, titledProps); - return null; - } - }; - txnHelper.doInTransaction(callback); - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err); - outcome = null; - ReportedException.throwIfNecessary(err); - } - - return outcome; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/categories/DeleteCategoryDialog.java b/war/src/main/java/org/alfresco/web/bean/categories/DeleteCategoryDialog.java deleted file mode 100644 index 6fea8ab7f4..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/categories/DeleteCategoryDialog.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.categories; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.transaction.RetryingTransactionHelper; -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.search.CategoryService; -import org.alfresco.service.cmr.search.CategoryService.Depth; -import org.alfresco.service.cmr.search.CategoryService.Mode; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.bean.categories.CategoriesDialog.CategoryBreadcrumbHandler; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.IBreadcrumbHandler; -import org.alfresco.web.ui.common.component.data.UIRichList; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.extensions.surf.util.ParameterCheck; - -public class DeleteCategoryDialog extends BaseDialogBean -{ - private static final long serialVersionUID = -8929785826091612856L; - - private static Log logger = LogFactory.getLog(DeleteCategoryDialog.class); - - private static final String DEFAULT_OUTCOME = "finish"; - private final static String MSG_DELETE_CATEGORY = "delete_category"; - private final static String MSG_DELETE = "delete"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - private static final String MSG_CATEGORIES = "categories"; - - transient protected CategoryService categoryService; - - /** Dialog properties */ - private String name = null; - private String description = null; - - /** Category path breadcrumb location */ - private List location = null; - - /** Members of the linked items of a category */ - private Collection members = null; - - /** Current category ref */ - private NodeRef categoryRef = null; - - /** Action category node */ - private Node actionCategory = null; - - /** Component references */ - protected UIRichList categoriesRichList; - - /** Currently visible category Node */ - private Node category = null; - - private Boolean categoryFlag = false; - - - @Override - public void init(Map parameters) - { - this.isFinished = false; - this.categoryFlag = false; - - // retrieve parameters - String categoryRef = parameters.get(CategoriesDialog.PARAM_CATEGORY_REF); - - // make sure nodeRef was supplied - ParameterCheck.mandatoryString(CategoriesDialog.PARAM_CATEGORY_REF, categoryRef); - - // create the node - this.category = new Node(new NodeRef(categoryRef)); - - setActionCategory(category); - } - - @Override - protected String doPostCommitProcessing(FacesContext context, String outcome) - { - // add the category to the request object so it gets picked up by - // category dialog, this will allow it to be removed from the breadcrumb - context.getExternalContext().getRequestMap().put( - CategoriesDialog.KEY_CATEGORY, this.category.getName()); - context.getExternalContext().getRequestMap().put( - CategoriesDialog.KEY_CATEGORY_FLAG, this.categoryFlag.toString()); - - return outcome; - } - - public Collection getMembers() - { - return members; - } - - public void setMembers(Collection members) - { - this.members = members; - } - - public int getMembersSize() - { - return getMembers().size(); - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name; - } - - public String getDescription() - { - return description; - } - - public void setDescription(String description) - { - this.description = description; - } - - /** - * @return the categoryService - */ - private CategoryService getCategoryService() - { - //check for null in cluster environment - if(categoryService == null) - { - categoryService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getCategoryService(); - } - return categoryService; - } - - public void setCategoryService(CategoryService categoryService) - { - this.categoryService = categoryService; - } - - public NodeRef getCategoryRef() - { - return categoryRef; - } - - public void setCategoryRef(NodeRef categoryRef) - { - this.categoryRef = categoryRef; - } - - public Node getCategory() - { - return category; - } - - public void setCategory(Node category) - { - this.category = category; - } - - public Boolean getCategoryFlag() - { - return categoryFlag; - } - - public void setCategoryFlag(Boolean categoryFlag) - { - this.categoryFlag = categoryFlag; - } - - /** - * @param node Set the Node to be used for the current category screen action. - */ - @SuppressWarnings("unchecked") - public void setActionCategory(Node node) - { - this.actionCategory = node; - - if (node != null) - { - // setup form properties - setName(node.getName()); - setDescription((String)node.getProperties().get(ContentModel.PROP_DESCRIPTION)); - setMembers(getCategoryService().getChildren(node.getNodeRef(), Mode.MEMBERS, Depth.ANY)); - } - else - { - setName(null); - setDescription(null); - Object emptyCollection = Collections.emptyList(); - setMembers((Collection) emptyCollection); - } - } - - public Node getActionCategory() - { - return actionCategory; - } - - public void setLocation(List location) - { - this.location = location; - } - - /** - * @return Breadcrumb location list - */ - public List getLocation() - { - return this.location; - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - finishDelete(); - return outcome; - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_DELETE_CATEGORY) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) - + getActionCategory().getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - @Override - public String getFinishButtonLabel() - { - - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_DELETE); - } - - public UIRichList getCategoriesRichList() - { - return categoriesRichList; - } - - public void setCategoriesRichList(UIRichList categoriesRichList) - { - this.categoriesRichList = categoriesRichList; - } - - /** - * @see org.alfresco.web.app.context.IContextListener#contextUpdated() - */ - public void contextUpdated() - { - if (logger.isDebugEnabled()) - logger.debug("Invalidating Category Management Components..."); - - // force a requery of the current category ref properties - setCategory(null); - - // force a requery of the richlist dataset - if (this.categoriesRichList != null) - { - this.categoriesRichList.setValue(null); - } - - } - - /** - * @return The ID of the currently displayed category or null if at the root. - */ - public String getCurrentCategoryId() - { - if (getCategoryRef() != null) - { - return getCategoryRef().getId(); - } - else - { - return null; - } - } - - /** - * Set the current category node. - *

- * Setting this value causes the UI to update and display the specified node as current. - * - * @param ref The current category node. - */ - public void setCurrentCategory(NodeRef ref) - { - if (logger.isDebugEnabled()) - logger.debug("Setting current category: " + ref); - - // set the current NodeRef for our UI context operations - setCategoryRef(ref); - - // clear current node context - setCategory(null); - - // inform that the UI needs updating after this change - contextUpdated(); - } - - - public String finishDelete() - { - String outcome = DEFAULT_OUTCOME; - - if (getActionCategory() != null) - { - try - { - FacesContext context = FacesContext.getCurrentInstance(); - RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(context); - RetryingTransactionCallback callback = new RetryingTransactionCallback() - { - @SuppressWarnings("unchecked") - public NodeRef execute() throws Throwable - { - // delete the category node using the nodeservice - NodeRef categoryNodeRef = getActionCategory().getNodeRef(); - getCategoryService().deleteCategory(categoryNodeRef); - - // if there are other items in the repository using this category - // all the associations to the category should be removed too - if (getMembers() != null && getMembers().size() > 0) - { - for (ChildAssociationRef childRef : getMembers()) - { - List list = new ArrayList(getMembers().size()); - - NodeRef member = childRef.getChildRef(); - Collection categories = (Collection)getNodeService().getProperty(member, ContentModel.PROP_CATEGORIES); - - for (NodeRef category : categories) - { - if (category.equals(categoryNodeRef) == false) - { - list.add(category); - } - } - - // persist the list back to the repository - getNodeService().setProperty(member, ContentModel.PROP_CATEGORIES, (Serializable) list); - } - } - return categoryNodeRef; - } - }; - NodeRef categoryNodeRef = txnHelper.doInTransaction(callback); - - // Figure out if the deletion is made by an icon or by a list of actions - CategoriesDialog categoriesDialog = (CategoriesDialog) UIContextService.getInstance(FacesContext.getCurrentInstance()) - .getRegisteredBean(CategoriesDialog.CATEGORIES_DIALOG_CLASS_NAME); - setLocation(categoriesDialog.getLocation()); - List location = getLocation(); - CategoryBreadcrumbHandler handler = (CategoryBreadcrumbHandler) location.get(location.size() - 1); - setCategoryFlag(!handler.toString().equals(getCategory().getName())); - - // clear action context - setActionCategory(null); - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err); - outcome = null; - ReportedException.throwIfNecessary(err); - } - } - - return outcome; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/categories/EditCategoryDialog.java b/war/src/main/java/org/alfresco/web/bean/categories/EditCategoryDialog.java deleted file mode 100644 index f601baac42..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/categories/EditCategoryDialog.java +++ /dev/null @@ -1,332 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.categories; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.search.CategoryService; -import org.alfresco.service.cmr.search.CategoryService.Depth; -import org.alfresco.service.cmr.search.CategoryService.Mode; -import org.alfresco.service.namespace.QName; -import org.springframework.extensions.surf.util.ParameterCheck; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.bean.categories.CategoriesDialog.CategoryBreadcrumbHandler; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.IBreadcrumbHandler; -import org.alfresco.web.ui.common.component.data.UIRichList; -import org.alfresco.web.ui.repo.component.IRepoBreadcrumbHandler; - -public class EditCategoryDialog extends BaseDialogBean -{ - private static final long serialVersionUID = 3316665625854694278L; - - private static final String DEFAULT_OUTCOME = "finish"; - private final static String MSG_EDIT_CATEGORY = "edit_category"; - private final static String MSG_FINISH = "finish_button"; - private static final String MSG_CATEGORIES = "categories"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - transient protected CategoryService categoryService; - - /** Action category node */ - private Node actionCategory = null; - - /** Currently visible category Node */ - private Node category = null; - - private Boolean categoryFlag = false; - - String categoryRef = null; - - /** Category path breadcrumb location */ - private List location = null; - - /** Members of the linked items of a category */ - private Collection members = null; - - /** Component references */ - protected UIRichList categoriesRichList; - - /** Dialog properties */ - private String name = null; - private String description = null; - - @Override - public void init(Map parameters) - { - this.isFinished = false; - this.categoryFlag = false; - - // retrieve parameters - categoryRef = parameters.get(CategoriesDialog.PARAM_CATEGORY_REF); - - // make sure nodeRef was supplied - ParameterCheck.mandatoryString(CategoriesDialog.PARAM_CATEGORY_REF, categoryRef); - - // create the node - this.category = new Node(new NodeRef(categoryRef)); - - setActionCategory(category); - } - - @Override - protected String doPostCommitProcessing(FacesContext context, String outcome) - { - // add the category to the request object so it gets picked up by - // category dialog, this will allow it to be edited in the breadcrumb - context.getExternalContext().getRequestMap().put( - CategoriesDialog.KEY_CATEGORY, this.category.getName()); - context.getExternalContext().getRequestMap().put( - CategoriesDialog.KEY_CATEGORY_FLAG, this.categoryFlag.toString()); - - return outcome; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name; - } - - public String getDescription() - { - return description; - } - - public void setDescription(String description) - { - this.description = description; - } - - public UIRichList getCategoriesRichList() - { - return categoriesRichList; - } - - public void setCategoriesRichList(UIRichList categoriesRichList) - { - this.categoriesRichList = categoriesRichList; - } - - /** - * @return the categoryService - */ - private CategoryService getCategoryService() - { - //check for null in cluster environment - if(categoryService == null) - { - categoryService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getCategoryService(); - } - return categoryService; - } - - public void setCategoryService(CategoryService categoryService) - { - this.categoryService = categoryService; - } - - public Node getCategory() - { - return category; - } - - public void setCategory(Node category) - { - this.category = category; - } - - public Boolean getCategoryFlag() - { - return categoryFlag; - } - - public void setCategoryFlag(Boolean categoryFlag) - { - this.categoryFlag = categoryFlag; - } - - public Collection getMembers() - { - return members; - } - - public void setMembers(Collection members) - { - this.members = members; - } - - @SuppressWarnings("unchecked") - public void setActionCategory(Node node) - { - this.actionCategory = node; - - if (node != null) - { - // setup form properties - setName(node.getName()); - setDescription((String) node.getProperties().get(ContentModel.PROP_DESCRIPTION)); - setMembers(getCategoryService().getChildren(node.getNodeRef(), Mode.MEMBERS, Depth.ANY)); - } - else - { - setName(null); - setDescription(null); - Object emptyCollection = Collections.emptyList(); - setMembers((Collection) emptyCollection); - } - } - - public Node getActionCategory() - { - return actionCategory; - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - - finishEdit(); - return outcome; - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_EDIT_CATEGORY) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) - + getActionCategory().getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - @Override - public String getFinishButtonLabel() - { - - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_FINISH); - } - - public void setLocation(List location) - { - this.location = location; - } - - /** - * @return Breadcrumb location list - */ - public List getLocation() - { - return this.location; - } - - public String finishEdit() - { - String outcome = DEFAULT_OUTCOME; - - try - { - - // update the category node - NodeRef nodeRef = getActionCategory().getNodeRef(); - getNodeService().setProperty(nodeRef, ContentModel.PROP_NAME, getName()); - - // ALF-1788 Need to rename the association - ChildAssociationRef assocRef = getNodeService().getPrimaryParent(nodeRef); - QName qname = QName.createQName( - assocRef.getQName().getNamespaceURI(), - QName.createValidLocalName(name)); - getNodeService().moveNode( - assocRef.getChildRef(), - assocRef.getParentRef(), - assocRef.getTypeQName(), - qname); - - // apply the titled aspect - for description - if (getNodeService().hasAspect(nodeRef, ContentModel.ASPECT_TITLED) == false) - { - Map titledProps = new HashMap(1, 1.0f); - titledProps.put(ContentModel.PROP_DESCRIPTION, getDescription()); - getNodeService().addAspect(nodeRef, ContentModel.ASPECT_TITLED, titledProps); - } - else - { - getNodeService().setProperty(nodeRef, ContentModel.PROP_DESCRIPTION, getDescription()); - } - - //Figure out if the editing is made by an icon or by a list of actions - CategoriesDialog categoriesDialog = (CategoriesDialog) UIContextService.getInstance(FacesContext.getCurrentInstance()) - .getRegisteredBean(CategoriesDialog.CATEGORIES_DIALOG_CLASS_NAME); - setLocation(categoriesDialog.getLocation()); - List location = getLocation(); - CategoryBreadcrumbHandler handler = (CategoryBreadcrumbHandler) location.get(location.size() - 1); - if (!handler.toString().equals(getCategory().getName())) - { - setCategoryFlag(true); - } - else - { - setCategoryFlag(false); - } - Node categoryNode = new Node(nodeRef); - setCategory(categoryNode); - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err); - outcome = null; - ReportedException.throwIfNecessary(err); - } - - return outcome; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/categories/EditNodeCategoriesDialog.java b/war/src/main/java/org/alfresco/web/bean/categories/EditNodeCategoriesDialog.java deleted file mode 100644 index fa8e71b9b3..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/categories/EditNodeCategoriesDialog.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.categories; - -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.QName; -import org.springframework.extensions.surf.util.ParameterCheck; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Node; - -/** - * Implementation for the edit node categories dialog. - * - * @author gavinc - */ -public class EditNodeCategoriesDialog extends BaseDialogBean -{ - private static final long serialVersionUID = -1879847736997772606L; - - protected Node node; - protected NodeRef addedCategory; - protected List categories; - protected String description; - - private static final String MSG_ERROR_UPDATE_CATEGORY = "error_update_category"; - private static final String MSG_MODIFY_CATEGORIES_OF = "modify_categories_of"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - // ------------------------------------------------------------------------------ - // Dialog implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - // reset variables - this.categories = null; - this.addedCategory = null; - - // retrieve parameters - String nodeRef = parameters.get("nodeRef"); - - // make sure nodeRef was supplied - ParameterCheck.mandatoryString("nodeRef", nodeRef); - - // create the node - this.node = new Node(new NodeRef(nodeRef)); - - // determine description for dialog - FacesContext context = FacesContext.getCurrentInstance(); - if (getDictionaryService().isSubClass(this.node.getType(), ContentModel.TYPE_FOLDER)) - { - this.description = Application.getMessage(context, "editcategory_space_description"); - } - else - { - this.description = Application.getMessage(context, "editcategory_description"); - } - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - // firstly retrieve all the properties for the current node - Map updateProps = getNodeService().getProperties(this.node.getNodeRef()); - - // create a node ref representation of the selected id and set the new properties - updateProps.put(ContentModel.PROP_CATEGORIES, (Serializable) categories); - - // set the properties on the node - getNodeService().setProperties(this.node.getNodeRef(), updateProps); - - return outcome; - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_MODIFY_CATEGORIES_OF) + - " " + Application.getMessage(fc, MSG_LEFT_QUOTE) + this.node.getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - @Override - public String getContainerDescription() - { - return this.description; - } - - @Override - protected String getErrorMessageId() - { - return MSG_ERROR_UPDATE_CATEGORY; - } - - // ------------------------------------------------------------------------------ - // Bean property getters and setters - - /** - * Returns a Map of the initial categories on the node keyed by the NodeRef - * - * @return Map of initial categories - */ - public List getCategories() - { - if (this.categories == null) - { - // get the list of categories - this.categories = (List)getNodeService().getProperty(this.node.getNodeRef(), - ContentModel.PROP_CATEGORIES); - } - - return this.categories; - } - - /** - * Sets the categories Map - * - * @param categories List - */ - public void setCategories(List categories) - { - this.categories = categories; - } - - /** - * Returns the last category added from the multi value editor - * - * @return The last category added - */ - public NodeRef getAddedCategory() - { - return this.addedCategory; - } - - /** - * Sets the category added from the multi value editor - * - * @param addedCategory The added category - */ - public void setAddedCategory(NodeRef addedCategory) - { - this.addedCategory = addedCategory; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/clipboard/AbstractClipboardItem.java b/war/src/main/java/org/alfresco/web/bean/clipboard/AbstractClipboardItem.java deleted file mode 100644 index daddd3084d..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/clipboard/AbstractClipboardItem.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.clipboard; - -import java.util.List; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.search.QueryParameterDefImpl; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.dictionary.DataTypeDefinition; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.search.QueryParameterDefinition; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.bean.repository.Repository; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Base class representing a single item added to the clipboard. - * - * @author Kevin Roast - */ -abstract class AbstractClipboardItem implements ClipboardItem -{ - protected static Log logger = LogFactory.getLog(ClipboardBean.class); - - protected static final String MSG_COPY_OF = "copy_of"; - - /** Shallow search for nodes with a name pattern */ - private static final String XPATH_QUERY_NODE_MATCH = "./*[like(@cm:name, $cm:name, false)]"; - - transient private ServiceRegistry services = null; - - protected NodeRef ref; - protected NodeRef parent; - protected ClipboardStatus mode; - - // cached values - private String name; - private QName type; - private String icon; - - private List customPasteViewIds; - - - /** - * Constructor - * - * @param ref The ref of the item on the clipboard - * @param mode The ClipboardStatus enum value - */ - public AbstractClipboardItem(NodeRef ref, ClipboardStatus mode, List customPasteViewIds) - { - this.ref = ref; - this.mode = mode; - this.customPasteViewIds = customPasteViewIds; - } - - /** - * Constructor - * - * @param ref The ref of the item on the clipboard - * @param parent The parent of the item on the clipboard - * @param mode The ClipboardStatus enum value - */ - public AbstractClipboardItem(NodeRef ref, NodeRef parent, ClipboardStatus mode, List customPasteViewIds) - { - this.ref = ref; - this.mode = mode; - this.parent = parent; - this.customPasteViewIds = customPasteViewIds; - } - - public ClipboardStatus getMode() - { - return this.mode; - } - - public String getName() - { - if (this.name == null) - { - this.name = (String)getServiceRegistry().getNodeService().getProperty( - this.ref, ContentModel.PROP_NAME); - } - return this.name; - } - - public QName getType() - { - if (this.type == null) - { - this.type = getServiceRegistry().getNodeService().getType(this.ref); - } - return this.type; - } - - public String getIcon() - { - if (this.icon == null) - { - this.icon = (String)getServiceRegistry().getNodeService().getProperty( - this.ref, ApplicationModel.PROP_ICON); - } - return this.icon; - } - - public NodeRef getNodeRef() - { - return this.ref; - } - - public NodeRef getParent() - { - return this.parent; - } - - /** - * Override equals() to compare NodeRefs - */ - public boolean equals(Object obj) - { - if (obj == this) - { - return true; - } - if (obj instanceof ClipboardItem) - { - return ((ClipboardItem)obj).getNodeRef().equals(this.ref); - } - else - { - return false; - } - } - - /** - * Override hashCode() to use the internal NodeRef hashcode instead - */ - public int hashCode() - { - return ref.hashCode(); - } - - protected ServiceRegistry getServiceRegistry() - { - if (services == null) - { - services = Repository.getServiceRegistry(FacesContext.getCurrentInstance()); - } - return services; - } - - public boolean canCopyToViewId(String viewId) - { - if (this.customPasteViewIds != null) - { - return this.customPasteViewIds.contains(viewId); - } - return false; - } - - public boolean canMoveToViewId(String viewId) - { - if (this.customPasteViewIds != null) - { - return this.customPasteViewIds.contains(viewId); - } - return false; - } - - protected boolean checkExists(String name, NodeRef parent) - { - QueryParameterDefinition[] params = new QueryParameterDefinition[1]; - params[0] = new QueryParameterDefImpl( - ContentModel.PROP_NAME, - getServiceRegistry().getDictionaryService().getDataType( - DataTypeDefinition.TEXT), - true, - name); - - // execute the query - List nodeRefs = getServiceRegistry().getSearchService().selectNodes( - parent, - XPATH_QUERY_NODE_MATCH, - params, - getServiceRegistry().getNamespaceService(), - false); - - return (nodeRefs.size() != 0); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/clipboard/ClipboardBean.java b/war/src/main/java/org/alfresco/web/bean/clipboard/ClipboardBean.java deleted file mode 100644 index 3fcb903b7a..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/clipboard/ClipboardBean.java +++ /dev/null @@ -1,371 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.clipboard; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.faces.application.FacesMessage; -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.repository.StoreRef; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.alfresco.web.ui.repo.component.shelf.UIClipboardShelfItem; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean backing the Clipboard shelf functionality. - *

- * The clipboard bean is responsible for processing Cut/Copy requests to the clipboard - * and for executing the various Paste calls available to the user. - * - * @author Kevin Roast - */ -public class ClipboardBean implements Serializable -{ - private static final long serialVersionUID = -6299320341615099651L; - - private static Log logger = LogFactory.getLog(ClipboardBean.class); - - /** I18N messages */ - private static final String MSG_ERROR_PASTE = "error_paste"; - private static final String MSG_VIEW_FOR_PASTE_WARN = "not_suitable_view_for_paste_warn"; - - /** Current state of the clipboard items */ - private List items = new ArrayList(4); - - transient private NodeService nodeService; - - private List customPasteViewIds; - - // ------------------------------------------------------------------------------ - // Bean property getters and setters - - /** - * @return Returns a list representing the items on the user clipboard. - */ - public List getItems() - { - return this.items; - } - - /** - * @param items List representing the items on the user clipboard. - */ - public void setItems(List items) - { - this.items = items; - } - - public void setNodeService(NodeService nodeService) - { - - this.nodeService = nodeService; - } - - private NodeService getNodeService() - { - if (nodeService == null) - { - nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - } - return nodeService; - } - - public void setCustomPasteViewIds(List customPasteViewIds) - { - this.customPasteViewIds = customPasteViewIds; - } - - public List getCustomPasteViewIds() - { - return customPasteViewIds; - } - - // ------------------------------------------------------------------------------ - // Navigation action event handlers - - /** - * Action handler called to add a node to the clipboard for a Copy operation - */ - public void copyNode(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String ref = params.get("ref"); - if (ref != null && ref.length() != 0) - { - addClipboardNode(new NodeRef(ref), null, ClipboardStatus.COPY); - } - } - - /** - * Action handler called to add a node to the clipboard for a Cut operation - */ - public void cutNode(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String ref = params.get("ref"); - String parent = params.get("parent"); - if (ref != null && ref.length() != 0) - { - NodeRef parentNodeRef = null; - if (parent != null) - { - parentNodeRef = new NodeRef(Repository.getStoreRef(), parent); - // ALF-8885 fix, if copied node is the same as parent node we should use null. - // Primary parent will be used later in FileFolderService#moveOrCopy method - if (parentNodeRef.toString().equals(ref)) - { - parentNodeRef = null; - } - } - addClipboardNode(new NodeRef(ref), parentNodeRef, ClipboardStatus.CUT); - } - } - - /** - * Action handler call from the browse screen to Paste All clipboard items into the current Space - */ - public void pasteAll(ActionEvent event) - { - performPasteItems(-1, UIClipboardShelfItem.ACTION_PASTE_ALL); - } - - /** - * Action handler called to paste one or all items from the clipboard - */ - public void pasteItem(ActionEvent event) - { - UIClipboardShelfItem.ClipboardEvent clipEvent = (UIClipboardShelfItem.ClipboardEvent)event; - - int index = clipEvent.Index; - if (index >= this.items.size()) - { - throw new IllegalStateException("Clipboard attempting paste a non existent item index: " + index); - } - - performPasteItems(index, clipEvent.Action); - } - - /** - * Perform a paste for the specified clipboard item(s) - * - * @param index of clipboard item to paste or -1 for all - * @param action the clipboard action to perform (see UIClipboardShelfItem) - */ - private void performPasteItems(int index, int action) - { - FacesContext context = FacesContext.getCurrentInstance(); - boolean toClear = false; - try - { - if (index == -1) - { - // paste all - List toRemove = new ArrayList(); - for (ClipboardItem item : this.items) - { - if (!getNodeService().exists(item.getNodeRef())) - { - toRemove.add(item); - toClear = true; - continue; - } - - if (performClipboardOperation(item, action) == true) - { - // if cut operation then remove item from the clipboard - if (item.getMode() == ClipboardStatus.CUT) - { - // remember which items to remove. - toRemove.add(item); - } - toClear = true; - } - } - - // clear the clipboard after a paste all - if (toClear) - { - if (Application.getClientConfig(context).isPasteAllAndClearEnabled()) - { - this.items.clear(); - } - else if (toRemove.size() > 0) - { - // remove the items that were cut above - for (ClipboardItem item : toRemove) - { - this.items.remove(item); - } - } - } - } - else - { - // single paste operation - ClipboardItem item = this.items.get(index); - if (performClipboardOperation(item, action) == true) - { - // if cut operation then remove item from the clipboard - if (item.getMode() == ClipboardStatus.CUT) - { - this.items.remove(index); - } - } - } - - // refresh UI on success - UIContextService.getInstance(context).notifyBeans(); - } - catch (Throwable err) - { - Utils.addErrorMessage(Application.getMessage(context, MSG_ERROR_PASTE) + err.getMessage(), err); - } - } - - /** - * Perform the operation for the specified clipboard item - * - * @param item the ClipboardItem - * @param action the clipboard action to perform (see UIClipboardShelfItem) - * - * @return true on successful operation - */ - private boolean performClipboardOperation(ClipboardItem item, int action) - throws Throwable - { - boolean success = false; - - FacesContext fc = FacesContext.getCurrentInstance(); - - // test the current JSF view to see if the clipboard item can paste to it - if (logger.isDebugEnabled()) - logger.debug("Clipboard destination View Id: " + fc.getViewRoot().getViewId()); - if (item.getMode() == ClipboardStatus.CUT) - { - if (item.canMoveToViewId(fc.getViewRoot().getViewId()) == true) - { - success = item.paste(fc, fc.getViewRoot().getViewId(), action); - } - else - { - if (Application.getClientConfig(fc).isClipboardStatusVisible()) - { - String pattern = Application.getMessage(fc, MSG_VIEW_FOR_PASTE_WARN); - String msg = MessageFormat.format(pattern, item.getName()); - FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_WARN, msg, msg); - fc.addMessage(null, facesMsg); - } - // we cannot support this view as a Move paste location - if (logger.isDebugEnabled()) - logger.debug("Clipboard Item: " + item.getNodeRef() + " not suitable for Move paste to current View Id."); - } - } - else if (item.getMode() == ClipboardStatus.COPY) - { - if (item.canCopyToViewId(fc.getViewRoot().getViewId()) == true) - { - success = item.paste(fc, fc.getViewRoot().getViewId(), action); - } - else - { - if (Application.getClientConfig(fc).isClipboardStatusVisible()) - { - String pattern = Application.getMessage(fc, MSG_VIEW_FOR_PASTE_WARN); - String msg = MessageFormat.format(pattern, item.getName()); - FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_WARN, msg, msg); - fc.addMessage(null, facesMsg); - } - // we cannot support this view as a Copy paste location - if (logger.isDebugEnabled()) - logger.debug("Clipboard Item: " + item.getNodeRef() + " not suitable for Copy paste to current View Id."); - } - } - - return success; - } - - /** - * Add a clipboard node to the clipboard ready for a cut/copy operation - * - * @param ref NodeRef of the item for the operation - * @param parent Parent of the item for the operation - * @param mode ClipboardStatus for the operation - */ - private void addClipboardNode(NodeRef ref, NodeRef parent, ClipboardStatus mode) - { - // construct item based on store protocol - ClipboardItem item = null; - if (StoreRef.PROTOCOL_WORKSPACE.equals(ref.getStoreRef().getProtocol())) - { - item = new WorkspaceClipboardItem(ref, parent, mode, customPasteViewIds); - } - if (item != null) - { - // check for duplicates first - boolean foundDuplicate = false; - for (int i=0; i. - * #L% - */ -package org.alfresco.web.bean.clipboard; - -import java.io.Serializable; - -import javax.faces.context.FacesContext; - -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.QName; - -/** - * Simple class representing a single item added to the clipboard. - * - * @author Kevin Roast - */ -public interface ClipboardItem extends Serializable -{ - /** - * @return the mode status of the clipboard item, the enum can be either Cut or Copy - */ - public ClipboardStatus getMode(); - - /** - * @return display label (cm:name) of the clipboard item - */ - public String getName(); - - /** - * @return QName type of the clipboard item - */ - public QName getType(); - - /** - * @return the app:icon property of the clipboard item - */ - public String getIcon(); - - /** - * @return the NodeRef of the clipboard item - */ - public NodeRef getNodeRef(); - - /** - * @return true if the item on the clipboard supports linking (.url) as a link type - */ - public boolean supportsLink(); - - /** - * @param viewId JSF View Id to check against - * - * @return true if the clipboard item can be Copy pasted to the specified JSF view - */ - public boolean canCopyToViewId(String viewId); - - /** - * @param viewId JSF View Id to check against - * - * @return true if the clipboard item can be Move pasted to the specified JSF view - */ - public boolean canMoveToViewId(String viewId); - - /** - * @param fc FacesContext - * @param viewId JSF View Id to paste into - * @param action Clipboard action constant (@see org.alfresco.web.ui.repo.component.shelf.UIClipboardShelfItem) - * - * @return true on successful paste, false otherwise - * - * @throws Throwable on fatal error during paste - */ - public boolean paste(FacesContext fc, String viewId, int action) throws Throwable; -} diff --git a/war/src/main/java/org/alfresco/web/bean/clipboard/ClipboardStatus.java b/war/src/main/java/org/alfresco/web/bean/clipboard/ClipboardStatus.java deleted file mode 100644 index 7385e565eb..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/clipboard/ClipboardStatus.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.clipboard; - -/** - * @author Kevin Roast - * - * Clipboard status for an item. - */ -public enum ClipboardStatus {CUT, COPY} diff --git a/war/src/main/java/org/alfresco/web/bean/clipboard/WorkspaceClipboardItem.java b/war/src/main/java/org/alfresco/web/bean/clipboard/WorkspaceClipboardItem.java deleted file mode 100644 index 60c03aca82..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/clipboard/WorkspaceClipboardItem.java +++ /dev/null @@ -1,344 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.clipboard; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.transaction.RetryingTransactionHelper; -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.ml.MultilingualContentService; -import org.alfresco.service.cmr.model.FileExistsException; -import org.alfresco.service.cmr.model.FileFolderService; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.CopyService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.NavigationBean; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.repo.component.shelf.UIClipboardShelfItem; - -/** - * Class representing a 'workspace' store protocol clipboard item - * - * @author Kevin Roast - */ -public class WorkspaceClipboardItem extends AbstractClipboardItem -{ - private static final long serialVersionUID = -1686557602737846009L; - - private static final String WORKSPACE_PASTE_VIEW_ID = "/jsp/browse/browse.jsp"; - private static final String FORUMS_PASTE_VIEW_ID = "/jsp/forums/forums.jsp"; - private static final String FORUM_PASTE_VIEW_ID = "/jsp/forums/forum.jsp"; - - private static final String MSG_LINK_TO = "link_to"; - - // File extension to use for link nodes - private static final String LINK_NODE_EXTENSION = ".url"; - - - /** - * @param ref - * @param mode - */ - public WorkspaceClipboardItem(NodeRef ref, ClipboardStatus mode, List customPasteViewIds) - { - super(ref, mode, customPasteViewIds); - } - - /** - * @param ref - * @param mode - */ - public WorkspaceClipboardItem(NodeRef ref, NodeRef parent, ClipboardStatus mode, List customPasteViewIds) - { - super(ref, parent, mode, customPasteViewIds); - } - - /** - * @see org.alfresco.web.bean.clipboard.ClipboardItem#supportsLink() - */ - public boolean supportsLink() - { - return true; - } - - /** - * @see org.alfresco.web.bean.clipboard.ClipboardItem#canCopyToViewId(java.lang.String) - */ - public boolean canCopyToViewId(String viewId) - { - return super.canCopyToViewId(viewId) || (WORKSPACE_PASTE_VIEW_ID.equals(viewId) || - FORUMS_PASTE_VIEW_ID.equals(viewId) || FORUM_PASTE_VIEW_ID.equals(viewId)); - } - - /** - * @see org.alfresco.web.bean.clipboard.ClipboardItem#canMoveToViewId(java.lang.String) - */ - public boolean canMoveToViewId(String viewId) - { - return super.canMoveToViewId(viewId) || (WORKSPACE_PASTE_VIEW_ID.equals(viewId) || FORUMS_PASTE_VIEW_ID.equals(viewId) || - FORUM_PASTE_VIEW_ID.equals(viewId)); - } - - /** - * @see org.alfresco.web.bean.clipboard.ClipboardItem#paste(javax.faces.context.FacesContext, java.lang.String, int) - */ - public boolean paste(final FacesContext fc, String viewId, final int action) - { - final ServiceRegistry serviceRegistry = getServiceRegistry(); - final RetryingTransactionHelper retryingTransactionHelper = serviceRegistry.getTransactionService().getRetryingTransactionHelper(); - if (super.canCopyToViewId(viewId) || WORKSPACE_PASTE_VIEW_ID.equals(viewId) || FORUMS_PASTE_VIEW_ID.equals(viewId) || - FORUM_PASTE_VIEW_ID.equals(viewId)) - { - NavigationBean navigator = (NavigationBean)FacesHelper.getManagedBean(fc, NavigationBean.BEAN_NAME); - final NodeRef destRef = new NodeRef(Repository.getStoreRef(), navigator.getCurrentNodeId()); - - final DictionaryService dd = serviceRegistry.getDictionaryService(); - final NodeService nodeService = serviceRegistry.getNodeService(); - final FileFolderService fileFolderService = serviceRegistry.getFileFolderService(); - final CopyService copyService = serviceRegistry.getCopyService(); - final MultilingualContentService multilingualContentService = serviceRegistry.getMultilingualContentService(); - - final boolean isPrimaryParent; - - final ChildAssociationRef assocRef; - - if (getParent() == null) - { - assocRef = nodeService.getPrimaryParent(getNodeRef()); - isPrimaryParent = true; - } - else - { - NodeRef parentNodeRef = getParent(); - List assocList = nodeService.getParentAssocs(getNodeRef()); - ChildAssociationRef foundRef = null; - if (assocList != null) - { - for (ChildAssociationRef assocListEntry : assocList) - { - if (parentNodeRef.equals(assocListEntry.getParentRef())) - { - foundRef = assocListEntry; - break; - } - } - } - assocRef = foundRef; - isPrimaryParent = parentNodeRef.equals(nodeService.getPrimaryParent(getNodeRef()).getParentRef()); - } - - // initial name to attempt the copy of the item with - String name = getName(); - String translationPrefix = ""; - - if (action == UIClipboardShelfItem.ACTION_PASTE_LINK) - { - // copy as link was specifically requested by the user - String linkTo = Application.getMessage(fc, MSG_LINK_TO); - name = linkTo + ' ' + name; - } - - // Loop until we find a target name that doesn't exist - for(;;) - { - try - { - final String currentTranslationPrefix = translationPrefix; - final String currentName = name; - - // attempt each copy/paste in its own transaction - retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback() - { - public Void execute() throws Throwable - { - if (getMode() == ClipboardStatus.COPY) - { - if (action == UIClipboardShelfItem.ACTION_PASTE_LINK) - { - // LINK operation - if (logger.isDebugEnabled()) - logger.debug("Attempting to link node ID: " + getNodeRef() + " into node: " + destRef.toString()); - - // we create a special Link Object node that has a property to reference the original - // create the node using the nodeService (can only use FileFolderService for content) - if (checkExists(currentName + LINK_NODE_EXTENSION, destRef) == false) - { - Map props = new HashMap(2, 1.0f); - String newName = currentName + LINK_NODE_EXTENSION; - props.put(ContentModel.PROP_NAME, newName); - props.put(ContentModel.PROP_LINK_DESTINATION, getNodeRef()); - if (dd.isSubClass(getType(), ContentModel.TYPE_CONTENT)) - { - // create File Link node - ChildAssociationRef childRef = nodeService.createNode( - destRef, - ContentModel.ASSOC_CONTAINS, - QName.createQName(assocRef.getQName().getNamespaceURI(), newName), - ApplicationModel.TYPE_FILELINK, - props); - - // apply the titled aspect - title and description - Map titledProps = new HashMap(2, 1.0f); - titledProps.put(ContentModel.PROP_TITLE, currentName); - titledProps.put(ContentModel.PROP_DESCRIPTION, currentName); - nodeService.addAspect(childRef.getChildRef(), ContentModel.ASPECT_TITLED, titledProps); - } - else - { - // create Folder link node - ChildAssociationRef childRef = nodeService.createNode( - destRef, - ContentModel.ASSOC_CONTAINS, - assocRef.getQName(), - ApplicationModel.TYPE_FOLDERLINK, - props); - - // apply the uifacets aspect - icon, title and description props - Map uiFacetsProps = new HashMap(4, 1.0f); - uiFacetsProps.put(ApplicationModel.PROP_ICON, "space-icon-link"); - uiFacetsProps.put(ContentModel.PROP_TITLE, currentName); - uiFacetsProps.put(ContentModel.PROP_DESCRIPTION, currentName); - nodeService.addAspect(childRef.getChildRef(), ApplicationModel.ASPECT_UIFACETS, uiFacetsProps); - } - } - } - else - { - // COPY operation - if (logger.isDebugEnabled()) - logger.debug("Attempting to copy node: " + getNodeRef() + " into node ID: " + destRef.toString()); - - // first check that we are not attempting to copy a duplicate into the same parent - if (destRef.equals(assocRef.getParentRef()) && currentName.equals(getName())) - { - // manually change the name if this occurs - throw new FileExistsException(destRef, currentName); - } - - if (dd.isSubClass(getType(), ContentModel.TYPE_CONTENT) || - dd.isSubClass(getType(), ContentModel.TYPE_FOLDER)) - { - // copy the file/folder - fileFolderService.copy( - getNodeRef(), - destRef, - currentName); - } - else if(dd.isSubClass(getType(), ContentModel.TYPE_MULTILINGUAL_CONTAINER)) - { - // copy the mlContainer and its translations - multilingualContentService.copyTranslationContainer(getNodeRef(), destRef, currentTranslationPrefix); - } - else - { - // copy the node - if (checkExists(currentName, destRef) == false) - { - copyService.copyAndRename( - getNodeRef(), - destRef, - ContentModel.ASSOC_CONTAINS, - assocRef.getQName(), - true); - } - } - } - } - else - { - // MOVE operation - if (logger.isDebugEnabled()) - logger.debug("Attempting to move node: " + getNodeRef() + " into node ID: " + destRef.toString()); - - if (dd.isSubClass(getType(), ContentModel.TYPE_CONTENT) || - dd.isSubClass(getType(), ContentModel.TYPE_FOLDER)) - { - // move the file/folder - fileFolderService.moveFrom(getNodeRef(), getParent(), destRef, currentName); - } - else if(dd.isSubClass(getType(), ContentModel.TYPE_MULTILINGUAL_CONTAINER)) - { - // copy the mlContainer and its translations - multilingualContentService.moveTranslationContainer(getNodeRef(), destRef); - } - else - { - if (isPrimaryParent) - { - // move the node - nodeService.moveNode(getNodeRef(), destRef, ContentModel.ASSOC_CONTAINS, assocRef.getQName()); - } - else - { - nodeService.removeChild(getParent(), getNodeRef()); - nodeService.addChild(destRef, getNodeRef(), assocRef.getTypeQName(), assocRef.getQName()); - } - } - } - return null; - } - }); - - // We got here without error, so no need to loop with a new name - break; - } - catch (FileExistsException fileExistsErr) - { - // If mode is COPY, have another go around the loop with a new name - if (getMode() == ClipboardStatus.COPY) - { - String copyOf = Application.getMessage(fc, MSG_COPY_OF); - name = copyOf + ' ' + name; - translationPrefix = copyOf + ' ' + translationPrefix; - } - else - { - // we should not rename an item when it is being moved - so exit - throw fileExistsErr; - } - } - } - return true; - } - else - { - return false; - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/coci/CCCheckinFileDialog.java b/war/src/main/java/org/alfresco/web/bean/coci/CCCheckinFileDialog.java deleted file mode 100644 index 2afe542037..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/coci/CCCheckinFileDialog.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.coci; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.Application; - -public class CCCheckinFileDialog extends CheckinCheckoutDialog -{ - - private static final long serialVersionUID = -3591701539727090905L; - - private static final String MSG_CHECK_IN = "check_in"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return checkinFileOK(context, outcome); - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CHECK_IN); - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_CHECK_IN) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) - + property.getDocument().getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - @Override - protected String getErrorOutcome(Throwable exception) - { - return "dialog:close"; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/coci/CCCheckoutFileDialog.java b/war/src/main/java/org/alfresco/web/bean/coci/CCCheckoutFileDialog.java deleted file mode 100644 index 5a0df022f6..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/coci/CCCheckoutFileDialog.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.coci; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.web.scripts.FileTypeImageUtils; -import org.alfresco.repo.workflow.WorkflowModel; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.workflow.WorkflowTask; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.servlet.DownloadContentServlet; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class CCCheckoutFileDialog extends CheckinCheckoutDialog -{ - private static final long serialVersionUID = 1137163500648349730L; - - public static final String LBL_SAVE = "save"; - public static final String LBL_CHECKOUT = "check_out"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - private static Log logger = LogFactory.getLog(CCCheckoutFileDialog.class); - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return checkoutFile(context, outcome); - - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - @Override - public String getFinishButtonLabel() - { - - return Application.getMessage(FacesContext.getCurrentInstance(), LBL_CHECKOUT); - } - - @Override - public String getContainerTitle() - { - final Node document = property.getDocument(); - if (document != null){ - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, LBL_CHECKOUT) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) - + document.getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - return null; - } - - /** - * Action called upon completion of the Check Out file page - */ - public String checkoutFile(FacesContext context, String outcome) - { - boolean checkoutSuccessful = false; - final Node node = property.getDocument(); - if (node != null) - { - try - { - if (logger.isDebugEnabled()) - logger.debug("Trying to checkout content node Id: " + node.getId()); - - // checkout the node content to create a working copy - if (logger.isDebugEnabled()) - { - logger.debug("Checkout copy location: " + property.getCopyLocation()); - logger.debug("Selected Space Id: " + property.getSelectedSpaceId()); - } - NodeRef workingCopyRef = null; - if (property.getCopyLocation().equals(CCProperties.COPYLOCATION_OTHER) && property.getSelectedSpaceId() != null) - { - // checkout to a arbituary parent Space - NodeRef destRef = property.getSelectedSpaceId(); - - ChildAssociationRef childAssocRef = getNodeService().getPrimaryParent(destRef); - workingCopyRef = property.getVersionOperationsService().checkout(node.getNodeRef(), destRef, ContentModel.ASSOC_CONTAINS, childAssocRef.getQName()); - } - else - { - // checkout the content to the current space - workingCopyRef = property.getVersionOperationsService().checkout(node.getNodeRef()); - - // if this is a workflow action and there is a task id - // present we need - // to also link the working copy to the workflow package so - // it appears - // in the resources panel in the manage task dialog - if (property.isWorkflowAction() && property.getWorkflowTaskId() != null && (property.getWorkflowTaskId().equals("null") == false)) - { - WorkflowTask task = property.getWorkflowService().getTaskById(property.getWorkflowTaskId()); - if (task != null) - { - NodeRef workflowPackage = (NodeRef) task.properties.get(WorkflowModel.ASSOC_PACKAGE); - if (workflowPackage != null) - { - getNodeService().addChild(workflowPackage, workingCopyRef, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, QName - .createValidLocalName((String) getNodeService().getProperty(workingCopyRef, ContentModel.PROP_NAME)))); - - if (logger.isDebugEnabled()) - logger.debug("Added working copy to workflow package: " + workflowPackage); - } - } - } - } - - // set the working copy Node instance - Node workingCopy = new Node(workingCopyRef); - property.setWorkingDocument(workingCopy); - - // create content URL to the content download servlet with ID - // and expected filename - // the myfile part will be ignored by the servlet but gives the - // browser a hint - String url = DownloadContentServlet.generateDownloadURL(workingCopyRef, workingCopy.getName()); - - workingCopy.getProperties().put("url", url); - workingCopy.getProperties().put("fileType32", FileTypeImageUtils.getFileTypeImage(workingCopy.getName(), false)); - - // mark as successful - checkoutSuccessful = true; - } - catch (Throwable err) - { - Utils.addErrorMessage(Application.getMessage(context, MSG_ERROR_CHECKOUT) + err.getMessage(), err); - ReportedException.throwIfNecessary(err); - } - } - else - { - logger.warn("WARNING: checkoutFile called without a current Document!"); - } - - // determine which page to show next if the checkout was successful. - if (checkoutSuccessful) - { - // If a check-in rule is present in the space - // the document was checked out to the working copy would have - // already disappeared! - if (getNodeService().exists(property.getWorkingDocument().getNodeRef())) - { - // go to the page that allows the user to download the content - // for editing - outcome = "dialog:checkoutFileLink"; // "checkoutFileLink"; - // //checkout-file-link.jsp - // currentAction = Action.CHECKOUT_FILE_LINK; - } - else - { - // show a page telling the user that the content has already - // been checked in - outcome = "dialog:workingCopyMissing";// "workingCopyMissing"; - // // - // working-copy-missing.jsp - // currentAction = Action.WORKING_COPY_MISSING; - } - } - return outcome; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/coci/CCCheckoutFileLinkDialog.java b/war/src/main/java/org/alfresco/web/bean/coci/CCCheckoutFileLinkDialog.java deleted file mode 100644 index 2e28687295..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/coci/CCCheckoutFileLinkDialog.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.coci; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class CCCheckoutFileLinkDialog extends CheckinCheckoutDialog -{ - private static final long serialVersionUID = -4732775752517417543L; - - public static final String MSG_CHECKOUT_OF = "check_out_of"; - public static final String LBL_UNDO_CHECKOUT = "undo_checkout"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - private static Log logger = LogFactory.getLog(CCCheckoutFileLinkDialog.class); - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return checkoutFileOK(context, outcome); - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_CHECKOUT_OF) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) - + property.getDocument().getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), LBL_UNDO_CHECKOUT); - } - - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "ok"); - } - - @Override - public String cancel() - { - undoCheckout(); - resetState(); - super.cancel(); - return "browse"; - - } - - /** - * Action called upon completion of the Check Out file Link download page - */ - public String checkoutFileOK(FacesContext context, String outcome) - { - Node node = property.getWorkingDocument(); - if (node != null) - { - // reset the underlying node - if (this.browseBean.getDocument() != null) - { - this.browseBean.getDocument().reset(); - } - - // clean up and clear action context - resetState(); - property.setDocument(null); - property.setWorkingDocument(null); - // currentAction = Action.NONE; - outcome = AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME + ":browse"; - } - else - { - logger.warn("WARNING: checkoutFileOK called without a current WorkingDocument!"); - } - return outcome; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/coci/CCEditFileDialog.java b/war/src/main/java/org/alfresco/web/bean/coci/CCEditFileDialog.java deleted file mode 100644 index d811c210bb..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/coci/CCEditFileDialog.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.coci; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.Application; - -public class CCEditFileDialog extends CheckinCheckoutDialog -{ - private static final long serialVersionUID = -1145049277343144264L; - - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - public static final String LBL_CLOSE = "close"; - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - - return super.cancel(); - } - - @Override - public String cancel() - { - property.setDocument(null); - property.setWorkingDocument(null); - resetState(); - return super.cancel(); - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), LBL_CLOSE); - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_LEFT_QUOTE) + property.getDocument().getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/coci/CCEditHtmlInlineDialog.java b/war/src/main/java/org/alfresco/web/bean/coci/CCEditHtmlInlineDialog.java deleted file mode 100644 index d721d2b580..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/coci/CCEditHtmlInlineDialog.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.coci; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.Application; - -public class CCEditHtmlInlineDialog extends CheckinCheckoutDialog -{ - private static final long serialVersionUID = 5971155828037579931L; - - public static final String LBL_SAVE = "save"; - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return editInline(context, outcome); - - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - @Override - public String getFinishButtonLabel() - { - - return Application.getMessage(FacesContext.getCurrentInstance(), LBL_SAVE); - } - - @Override - public String getContainerTitle() - { - return property.getDocument().getName(); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/coci/CCEditTextInlineDialog.java b/war/src/main/java/org/alfresco/web/bean/coci/CCEditTextInlineDialog.java deleted file mode 100644 index 9ee3d96660..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/coci/CCEditTextInlineDialog.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.coci; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.Application; - -public class CCEditTextInlineDialog extends CheckinCheckoutDialog -{ - private static final long serialVersionUID = 4657371875928010937L; - - public static final String LBL_SAVE = "save"; - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return editInline(context, outcome); - - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - @Override - public String getFinishButtonLabel() - { - - return Application.getMessage(FacesContext.getCurrentInstance(), LBL_SAVE); - } - - @Override - public String getContainerTitle() - { - return property.getDocument().getName(); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/coci/CCProperties.java b/war/src/main/java/org/alfresco/web/bean/coci/CCProperties.java deleted file mode 100644 index 1270b6c35e..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/coci/CCProperties.java +++ /dev/null @@ -1,431 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.coci; - -import java.io.File; -import java.io.Serializable; - -import javax.faces.context.FacesContext; - -import org.alfresco.service.cmr.coci.CheckOutCheckInService; -import org.alfresco.service.cmr.repository.ContentService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.version.VersionService; -import org.alfresco.service.cmr.workflow.WorkflowService; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; - -public class CCProperties implements Serializable -{ - - private static final long serialVersionUID = -79530354521757202L; - - /** The VersionOperationsService to be used by the bean */ - transient protected CheckOutCheckInService versionOperationsService; - - /** The VersionQueryService to be used by the bean */ - transient protected VersionService versionQueryService; - - /** The ContentService to be used by the bean */ - transient protected ContentService contentService; - - /** The WorkflowService to be used by the bean */ - transient protected WorkflowService workflowService; - - /** Content of the document returned from in-line editing */ - private String editorOutput; - - /** Content of the document used for HTML in-line editing */ - private String documentContent; - - /** The working copy of the document we are checking out */ - private Node workingDocument; - - /** The current document */ - private Node document; - - /** transient form and upload properties */ - private File file; - private String fileName; - private String webdavUrl; - private String cifsPath; - private boolean keepCheckedOut = false; - private boolean minorChange = true; - private boolean isWorkflowAction = false; - private String workflowTaskId; - private NodeRef selectedSpaceId = null; - - /** constants for copy location selection */ - public static final String COPYLOCATION_CURRENT = "current"; - public static final String COPYLOCATION_OTHER = "other"; - - private String versionNotes = ""; - private String copyLocation = COPYLOCATION_CURRENT; - - /** - * @return Returns the VersionOperationsService. - */ - public CheckOutCheckInService getVersionOperationsService() - { - //check for null in cluster environment - if (versionOperationsService == null) - { - versionOperationsService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getCheckOutCheckInService(); - } - return versionOperationsService; - } - - /** - * @param versionOperationsService - * The VersionOperationsService to set. - */ - public void setVersionOperationsService(CheckOutCheckInService versionOperationsService) - { - this.versionOperationsService = versionOperationsService; - } - - /** - * @return Returns the VersionQueryService. - */ - public VersionService getVersionQueryService() - { - if (this.versionQueryService == null) - { - this.versionQueryService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getVersionService(); - } - - return this.versionQueryService; - } - - /** - * @param versionQueryService - * The VersionQueryService to set. - */ - public void setVersionQueryService(VersionService versionQueryService) - { - this.versionQueryService = versionQueryService; - } - - /** - * @return Returns the ContentService. - */ - public ContentService getContentService() - { - //check for null in cluster environment - if (contentService == null) - { - contentService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getContentService(); - } - return contentService; - } - - /** - * @param contentService - * The ContentService to set. - */ - public void setContentService(ContentService contentService) - { - this.contentService = contentService; - } - - /** - * @param workflowService - * The WorkflowService to set. - */ - public void setWorkflowService(WorkflowService workflowService) - { - this.workflowService = workflowService; - } - - /** - * @return the workflowService - */ - public WorkflowService getWorkflowService() - { - //check for null for cluster environment - if (workflowService == null) - { - workflowService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getWorkflowService(); - } - return workflowService; - } - - /** - * @return Returns output from the in-line editor page. - */ - public String getEditorOutput() - { - return this.editorOutput; - } - - /** - * @param editorOutput - * The output from the in-line editor page - */ - public void setEditorOutput(String editorOutput) - { - this.editorOutput = editorOutput; - } - - /** - * @return Returns the document content used for HTML in-line editing. - */ - public String getDocumentContent() - { - return this.documentContent; - } - - /** - * @param documentContent - * The document content for HTML in-line editing. - */ - public void setDocumentContent(String documentContent) - { - this.documentContent = documentContent; - } - - /** - * @return Returns the working copy Document. - */ - public Node getWorkingDocument() - { - return this.workingDocument; - } - - /** - * @param workingDocument - * The working copy Document to set. - */ - public void setWorkingDocument(Node workingDocument) - { - this.workingDocument = workingDocument; - } - - /** - * @return The document node being used for the current operation - */ - public Node getDocument() - { - return this.document; - } - - /** - * @param document - * The document node to be used for the current operation - */ - public void setDocument(Node document) - { - this.document = document; - } - - /** - * @return Returns the selected Space Id. - */ - public NodeRef getSelectedSpaceId() - { - return this.selectedSpaceId; - } - - /** - * @param selectedSpaceId - * The selected Space Id to set. - */ - public void setSelectedSpaceId(NodeRef selectedSpaceId) - { - this.selectedSpaceId = selectedSpaceId; - } - - /** - * @return the file - */ - public File getFile() - { - return file; - } - - /** - * @param file the file to set - */ - public void setFile(File file) - { - this.file = file; - } - - /** - * @return the fileName - */ - public String getFileName() - { - return fileName; - } - - /** - * @param fileName the fileName to set - */ - public void setFileName(String fileName) - { - this.fileName = fileName; - } - - /** - * @param keepCheckedOut - * The keepCheckedOut to set. - */ - public void setKeepCheckedOut(boolean keepCheckedOut) - { - this.keepCheckedOut = keepCheckedOut; - } - - /** - * @return Returns the keepCheckedOut. - */ - public boolean getKeepCheckedOut() - { - return this.keepCheckedOut; - } - - /** - * @param minorChange - * The minorChange to set. - */ - public void setMinorChange(boolean minorChange) - { - this.minorChange = minorChange; - } - - /** - * @return Returns the minorChange flag. - */ - public boolean getMinorChange() - { - return this.minorChange; - } - - /** - * @return the isWorkflowAction - */ - public boolean isWorkflowAction() - { - return isWorkflowAction; - } - - /** - * @param isWorkflowAction the isWorkflowAction to set - */ - public void setWorkflowAction(boolean isWorkflowAction) - { - this.isWorkflowAction = isWorkflowAction; - } - - /** - * @return the workflowTaskId - */ - public String getWorkflowTaskId() - { - return workflowTaskId; - } - - /** - * @param workflowTaskId the workflowTaskId to set - */ - public void setWorkflowTaskId(String workflowTaskId) - { - this.workflowTaskId = workflowTaskId; - } - - /** - * @return Returns the version history notes. - */ - public String getVersionNotes() - { - return this.versionNotes; - } - - /** - * @param versionNotes - * The version history notes to set. - */ - public void setVersionNotes(String versionNotes) - { - this.versionNotes = versionNotes; - } - - /** - * @return Returns the copy location. Either the current or other space. - */ - public String getCopyLocation() - { - if (this.getFileName() == null || this.getFileName().length() == 0) - { - return this.copyLocation; - } - else - { - return CCProperties.COPYLOCATION_OTHER; - } - } - - /** - * @param copyLocation - * The copy location. Either the current or other space. - */ - public void setCopyLocation(String copyLocation) - { - this.copyLocation = copyLocation; - } - - /** - * @return Returns WebDav url for online editing. If webdav online editing didn't yet started, returns null - */ - public String getWebdavUrl() - { - return webdavUrl; - } - - /** - * @param webdavUrl The webdav url. Using only for online editing - */ - public void setWebdavUrl(String webdavUrl) - { - this.webdavUrl = webdavUrl; - } - - /** - * @return Returns CIFS path for online editing. If cifs online editing didn't yet started, returns null - */ - public String getCifsPath() - { - return cifsPath; - } - - /** - * @param cifsPath The cifs path. Using only for online editing - */ - public void setCifsPath(String cifsPath) - { - this.cifsPath = cifsPath; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/coci/CCUndoCheckoutFileDialog.java b/war/src/main/java/org/alfresco/web/bean/coci/CCUndoCheckoutFileDialog.java deleted file mode 100644 index ee30e8e677..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/coci/CCUndoCheckoutFileDialog.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.coci; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class CCUndoCheckoutFileDialog extends CheckinCheckoutDialog -{ - private static final long serialVersionUID = -6957120889259486975L; - - public static final String LBL_UNDO_CHECKOUT = "undo_checkout"; - public static final String MSG_UNDO_CHECKOUT_FOR = "undo_checkout_for"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - private static Log logger = LogFactory.getLog(CheckinCheckoutDialog.class); - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return undoCheckoutFile(context, outcome); - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_UNDO_CHECKOUT_FOR) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) - + property.getDocument().getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), LBL_UNDO_CHECKOUT); - - } - - /** - * Action to undo the checkout of a locked document. This document may - * either by the original copy or the working copy node. Therefore calculate - * which it is, if the working copy is found then we simply cancel checkout - * on that document. If the original copy is found then we need to find the - * appropriate working copy and perform the action on that node. - */ - public String undoCheckoutFile(FacesContext context, String outcome) - { - Node node = property.getDocument(); - if (node != null) - { - try - { - if (node.hasAspect(ContentModel.ASPECT_WORKING_COPY)) - { - this.property.getVersionOperationsService().cancelCheckout(node.getNodeRef()); - } - else if (node.hasAspect(ContentModel.ASPECT_LOCKABLE)) - { - // TODO: find the working copy for this document and cancel - // the checkout on it - // is this possible? as currently only the workingcopy - // aspect has the copyReference - // attribute - this means we cannot find out where the copy - // is to cancel it! - // can we construct an XPath node lookup? - throw new RuntimeException("NOT IMPLEMENTED"); - } - else - { - throw new IllegalStateException("Node supplied for undo checkout has neither Working Copy or Locked aspect!"); - } - - resetState(); - } - catch (Throwable err) - { - Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), MSG_ERROR_CANCELCHECKOUT) + err.getMessage(), err); - ReportedException.throwIfNecessary(err); - } - } - else - { - logger.warn("WARNING: undoCheckout called without a current WorkingDocument!"); - } - - return outcome + ":browse"; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/coci/CCUpdateFileDialog.java b/war/src/main/java/org/alfresco/web/bean/coci/CCUpdateFileDialog.java deleted file mode 100644 index 28036e4f68..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/coci/CCUpdateFileDialog.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.coci; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.bean.repository.Node; - -import org.alfresco.web.app.Application; - -public class CCUpdateFileDialog extends CheckinCheckoutDialog -{ - private static final long serialVersionUID = 8230565659041530809L; - - private final static String MSG_UPDATE = "update"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return updateFileOK(context, outcome); - } - - @Override - public String getContainerTitle() - { - Node document = property.getDocument(); - if(document != null) - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_UPDATE) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) - + document.getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - return null; - } - - @Override - public boolean getFinishButtonDisabled() - { - return getFileName() == null; - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_UPDATE); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/coci/CCWorkingCopyMissingDialog.java b/war/src/main/java/org/alfresco/web/bean/coci/CCWorkingCopyMissingDialog.java deleted file mode 100644 index db55a93410..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/coci/CCWorkingCopyMissingDialog.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.coci; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.app.Application; - -public class CCWorkingCopyMissingDialog extends CheckinCheckoutDialog -{ - private static final long serialVersionUID = 8067485292477557683L; - - public static final String MSG_WORKING_COPY_FOR = "working_copy_for"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - public static final String LBL_CLOSE = "close"; - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove(AlfrescoNavigationHandler.EXTERNAL_CONTAINER_SESSION); - - return getDefaultCancelOutcome(); - } - - @Override - public String cancel() - { - FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove(AlfrescoNavigationHandler.EXTERNAL_CONTAINER_SESSION); - - return AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME + ":browse"; - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_WORKING_COPY_FOR) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) - + property.getDocument().getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), LBL_CLOSE); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/coci/CancelEditingDialog.java b/war/src/main/java/org/alfresco/web/bean/coci/CancelEditingDialog.java deleted file mode 100644 index 2e92c7f0e8..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/coci/CancelEditingDialog.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.coci; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class CancelEditingDialog extends CheckinCheckoutDialog -{ - public static final String MSG_CANCEL_EDITING = "cancel_editing"; - public static final String MSG_CANCEL_EDITING_FOR = "cancel_editing_for"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - private static Log logger = LogFactory.getLog(CheckinCheckoutDialog.class); - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - undoCheckoutFile(context, outcome); - return outcome; - } - - @Override - protected String getDefaultCancelOutcome() - { - return AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME + - AlfrescoNavigationHandler.OUTCOME_SEPARATOR + - AlfrescoNavigationHandler.OUTCOME_BROWSE; - } - - @Override - protected String getDefaultFinishOutcome() - { - return AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME + - AlfrescoNavigationHandler.OUTCOME_SEPARATOR + - AlfrescoNavigationHandler.OUTCOME_BROWSE; - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_CANCEL_EDITING_FOR) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) - + property.getDocument().getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CANCEL_EDITING); - } - - /** - * Action to undo the checkout of a locked document. This document may - * either by the original copy or the working copy node. Therefore calculate - * which it is, if the working copy is found then we simply cancel checkout - * on that document. If the original copy is found then we need to find the - * appropriate working copy and perform the action on that node. - */ - public String undoCheckoutFile(FacesContext context, String outcome) - { - Node node = property.getDocument(); - if (node != null) - { - try - { - if (node.hasAspect(ContentModel.ASPECT_WORKING_COPY)) - { - this.property.getVersionOperationsService().cancelCheckout(node.getNodeRef()); - } - else if (node.hasAspect(ContentModel.ASPECT_LOCKABLE)) - { - // TODO: find the working copy for this document and cancel - // the checkout on it - // is this possible? as currently only the workingcopy - // aspect has the copyReference - // attribute - this means we cannot find out where the copy - // is to cancel it! - // can we construct an XPath node lookup? - throw new RuntimeException("NOT IMPLEMENTED"); - } - else - { - throw new IllegalStateException("Node supplied for undo checkout has neither Working Copy or Locked aspect!"); - } - - resetState(); - } - catch (Throwable err) - { - Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), MSG_ERROR_CANCELCHECKOUT) + err.getMessage(), err); - ReportedException.throwIfNecessary(err); - } - } - else - { - logger.warn("WARNING: undoCheckout called without a current WorkingDocument!"); - } - - return outcome; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/coci/CheckinCheckoutDialog.java b/war/src/main/java/org/alfresco/web/bean/coci/CheckinCheckoutDialog.java deleted file mode 100644 index 05ce5aee52..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/coci/CheckinCheckoutDialog.java +++ /dev/null @@ -1,648 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.coci; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.HashMap; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.AbortProcessingException; -import javax.faces.event.ActionEvent; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.repo.transaction.RetryingTransactionHelper; -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.repo.version.VersionModel; -import org.alfresco.repo.web.scripts.FileTypeImageUtils; -import org.alfresco.service.cmr.repository.ContentData; -import org.alfresco.service.cmr.repository.ContentReader; -import org.alfresco.service.cmr.repository.ContentWriter; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.version.Version; -import org.alfresco.service.cmr.version.VersionType; -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.app.servlet.DownloadContentServlet; -import org.alfresco.web.bean.BrowseBean; -import org.alfresco.web.bean.FileUploadBean; -import org.alfresco.web.bean.NavigationBean; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * @author Kevin Roast - */ -public class CheckinCheckoutDialog extends BaseDialogBean -{ - // ------------------------------------------------------------------------------ - // Private data - - private static final long serialVersionUID = -4898900470274506760L; - - private static Log logger = LogFactory.getLog(CheckinCheckoutDialog.class); - - /* /** I18N messages */ - public static final String MSG_ERROR_CHECKIN = "error_checkin"; - public static final String MSG_ERROR_CANCELCHECKOUT = "error_cancel_checkout"; - public static final String MSG_ERROR_UPDATE = "error_update"; - public static final String MSG_ERROR_CHECKOUT = "error_checkout"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - public static final String FILE = "file"; - - protected CCProperties property; - - // ------------------------------------------------------------------------------ - // Bean property getters and setters - - /** - * @param property the property to set - */ - public void setProperty(CCProperties property) - { - this.property = property; - } - - /** - * @param navigator The NavigationBean to set. - */ - public void setNavigator(NavigationBean navigator) - { - this.navigator = navigator; - } - - /** - * @return Returns the BrowseBean. - */ - public BrowseBean getBrowseBean() - { - return this.browseBean; - } - - /** - * @param browseBean The BrowseBean to set. - */ - public void setBrowseBean(BrowseBean browseBean) - { - this.browseBean = browseBean; - } - - public boolean getFinishButtonDisabled() - { - return false; - } - - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "check_in"); - } - - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, "check_in") + " " + - Application.getMessage(fc, MSG_LEFT_QUOTE)+ this.property.getDocument().getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - /** - * Determines whether the document being checked in has - * the versionable aspect applied - * - * @return true if the versionable aspect is applied - */ - public boolean isVersionable() - { - return property.getDocument().hasAspect(ContentModel.ASPECT_VERSIONABLE); - } - - /** - * @return Returns the message to display when a file has been uploaded - */ - public String getFileUploadSuccessMsg() - { - String msg = Application.getMessage(FacesContext.getCurrentInstance(), "file_upload_success"); - return MessageFormat.format(msg, new Object[] {Utils.encode(getFileName())}); - } - - /** - * @return Returns the name of the file - */ - public String getFileName() - { - // try and retrieve the file and filename from the file upload bean - // representing the file we previously uploaded. - FacesContext ctx = FacesContext.getCurrentInstance(); - FileUploadBean fileBean = (FileUploadBean)ctx.getExternalContext().getSessionMap(). - get(FileUploadBean.FILE_UPLOAD_BEAN_NAME); - if (fileBean != null) - { - property.setFile(fileBean.getFile()); - property.setFileName(fileBean.getFileName()); - } - - return property.getFileName(); - } - - /** - * @param fileName The name of the file - */ - public void setFileName(String fileName) - { - property.setFileName(fileName); - - // we also need to keep the file upload bean in sync - FacesContext ctx = FacesContext.getCurrentInstance(); - FileUploadBean fileBean = (FileUploadBean)ctx.getExternalContext().getSessionMap(). - get(FileUploadBean.FILE_UPLOAD_BEAN_NAME); - if (fileBean != null) - { - fileBean.setFileName(property.getFileName()); - } - } - - /** - * Clear the uploaded form, clearing the specific Upload component by Id - */ - protected void clearUpload(final String id) - { - // remove the file upload bean from the session - final FacesContext ctx = FacesContext.getCurrentInstance(); - FileUploadBean fileBean = (FileUploadBean) - ctx.getExternalContext().getSessionMap().get(FileUploadBean.FILE_UPLOAD_BEAN_NAME); - if (fileBean != null) - { - fileBean.setFile(null); - fileBean.setFileName(null); - } - } - - /** - * Action handler called when the user wishes to remove an uploaded file - */ - public String removeUploadedFile() - { - this.clearUpload(CheckinCheckoutDialog.FILE); - property.setFileName(null) ; - property.setFile(null); - return null; - } - - // ------------------------------------------------------------------------------ - // Navigation action event handlers - - /** - * Action event called by all actions that need to setup a Content Document context on the - * CheckinCheckoutDialog before an action page/wizard is called. The context will be a Node in - * setDocument() which can be retrieved on action pages via getDocument(). - * - * @param event ActionEvent - */ - public void setupContentAction(ActionEvent event) - { - UIActionLink link = (UIActionLink) event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - setupContentDocument(id); - } - else - { - property.setDocument(null); - } - - resetState(); - } - - public void setupWorkflowContentAction(ActionEvent event) - { - // do the common processing - setupContentAction(event); - - // retrieve the id of the task - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - property.setWorkflowTaskId(params.get("taskId")); - - property.setWorkflowAction(true); - - if (logger.isDebugEnabled()) - logger.debug("Setup for workflow package action for task id: " + property.getWorkflowTaskId()); - } - - /** - * Setup a content document node context - * - * @param id GUID of the node to setup as the content document context - * @return The Node - */ - protected Node setupContentDocument(String id) - { - if (logger.isDebugEnabled()) - logger.debug("Setup for action, setting current document to: " + id); - - Node node = null; - - try - { - // create the node ref, then our node representation - NodeRef ref = new NodeRef(Repository.getStoreRef(), id); - node = new Node(ref); - - // create content URL to the content download servlet with ID and expected filename - // the myfile part will be ignored by the servlet but gives the browser a hint - String url = DownloadContentServlet.generateDownloadURL(ref, node.getName()); - node.getProperties().put("url", url); - node.getProperties().put("workingCopy", node.hasAspect(ContentModel.ASPECT_WORKING_COPY)); - node.getProperties().put("fileType32", FileTypeImageUtils.getFileTypeImage(node.getName(), false)); - - // remember the document - property.setDocument(node); - - // refresh the UI, calling this method now is fine as it basically makes sure certain - // beans clear the state - so when we finish here other beans will have been reset - UIContextService.getInstance(FacesContext.getCurrentInstance()).notifyBeans(); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {id}) ); - throw new AbortProcessingException("Invalid node reference"); - } - - return node; - } - - /** - * Action handler called to calculate which editing screen to display based on the mimetype - * of a document. If appropriate, the in-line editing screen will be shown. - */ - public void editFile(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - try - { - if (id != null && id.length() != 0) - { - boolean editingInline = false; - Node node = setupContentDocument(id); - - if (node.hasAspect(ApplicationModel.ASPECT_INLINEEDITABLE) && - node.getProperties().get(ApplicationModel.PROP_EDITINLINE) != null && - ((Boolean)node.getProperties().get(ApplicationModel.PROP_EDITINLINE)).booleanValue() == true) - { - // retrieve the content reader for this node - ContentReader reader = property.getContentService().getReader(node.getNodeRef(), ContentModel.PROP_CONTENT); - if (reader != null) - { - editingInline = true; - String mimetype = reader.getMimetype(); - - // calculate which editor screen to display - if (MimetypeMap.MIMETYPE_TEXT_PLAIN.equals(mimetype) || - MimetypeMap.MIMETYPE_XML.equals(mimetype) || - MimetypeMap.MIMETYPE_TEXT_CSS.equals(mimetype) || - MimetypeMap.MIMETYPE_JAVASCRIPT.equals(mimetype)) - { - // make content available to the text editing screen - property.setEditorOutput(reader.getContentString()); - - // navigate to appropriate screen - FacesContext fc = FacesContext.getCurrentInstance(); - this.navigator.setupDispatchContext(node); - fc.getApplication().getNavigationHandler().handleNavigation(fc, null, "dialog:editTextInline"); - } - else - { - // make content available to the html editing screen - property.setDocumentContent(reader.getContentString()); - property.setEditorOutput(null); - - // navigate to appropriate screen - FacesContext fc = FacesContext.getCurrentInstance(); - this.navigator.setupDispatchContext(node); - fc.getApplication().getNavigationHandler().handleNavigation(fc, null, "dialog:editHtmlInline"); - } - } - } - - if (editingInline == false) - { - // normal downloadable document - FacesContext fc = FacesContext.getCurrentInstance(); - this.navigator.setupDispatchContext(node); - fc.getApplication().getNavigationHandler().handleNavigation(fc, null, "dialog:editFile"); - } - } - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {id}) ); - } - } - - /** - * Action handler called to set the content of a node from an inline editing page. - */ - public String editInline(FacesContext context, String outcome) - { - final Node node = property.getDocument(); - if (node != null) - { - try - { - if (logger.isDebugEnabled()) - logger.debug("Trying to update content node Id: " + node.getId()); - - // get an updating writer that we can use to modify the content on the current node - ContentWriter writer = property.getContentService().getWriter(node.getNodeRef(), ContentModel.PROP_CONTENT, true); - writer.putContent(property.getEditorOutput()); - - // clean up and clear action context - resetState(); - property.setDocument(null); - property.setDocumentContent(null); - property.setEditorOutput(null); - } - catch (Throwable err) - { - Utils.addErrorMessage(Application.getMessage( - FacesContext.getCurrentInstance(), MSG_ERROR_UPDATE) + err.getMessage()); - outcome = null; - ReportedException.throwIfNecessary(err); - } - } - else - { - logger.warn("WARNING: editInlineOK called without a current Document!"); - } - return outcome; - } - - /** - * Action to undo the checkout of a document just checked out from the checkout screen. - */ - public String undoCheckout() - { - String outcome = null; - - Node node = property.getWorkingDocument(); - if (node != null) - { - try - { - // try to cancel checkout of the working copy - this.property.getVersionOperationsService().cancelCheckout(node.getNodeRef()); - - resetState(); - - outcome = AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME; - } - catch (Throwable err) - { - Utils.addErrorMessage(Application.getMessage( - FacesContext.getCurrentInstance(), MSG_ERROR_CANCELCHECKOUT) + err.getMessage(), err); - ReportedException.throwIfNecessary(err); - } - } - else - { - logger.warn("WARNING: undoCheckout called without a current WorkingDocument!"); - } - - return outcome; - } - - /** - * Action called upon completion of the Check In file page - */ - public String checkinFileOK(final FacesContext context, String outcome) - { - - // NOTE: for checkin the document node _is_ the working document! - final Node node = property.getDocument(); - if (node != null && (property.getCopyLocation().equals(CCProperties.COPYLOCATION_CURRENT) || (this.getFileName() != null && !this.getFileName().equals("")))) - { - try - { - RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(FacesContext.getCurrentInstance()); - RetryingTransactionCallback callback = new RetryingTransactionCallback() - { - public Object execute() throws Throwable - { - if (logger.isDebugEnabled()) - logger.debug("Trying to checkin content node Id: " + node.getId()); - - // we can either checkin the content from the current working copy node - // which would have been previously updated by the user - String contentUrl; - if (property.getCopyLocation().equals(CCProperties.COPYLOCATION_CURRENT)) - { - ContentData contentData = (ContentData) node.getProperties().get(ContentModel.PROP_CONTENT); - contentUrl = (contentData == null ? null : contentData.getContentUrl()); - } - // or specify a specific file as the content instead - else - { - // add the content to an anonymous but permanent writer location - // we can then retrieve the URL to the content to to be set on the node during checkin - ContentWriter writer = property.getContentService().getWriter(node.getNodeRef(), ContentModel.PROP_CONTENT, true); - // also update the mime type in case a different type of file is uploaded - String mimeType = Repository.getMimeTypeForFileName(context, property.getFileName()); - writer.setMimetype(mimeType); - writer.putContent(property.getFile()); - contentUrl = writer.getContentUrl(); - } - - if (contentUrl == null || contentUrl.length() == 0) - { - throw new IllegalStateException("Content URL is empty for specified working copy content node!"); - } - - // add version history text to props - Map props = new HashMap(1, 1.0f); - props.put(Version.PROP_DESCRIPTION, property.getVersionNotes()); - // set the flag for minor or major change - if (property.getMinorChange()) - { - props.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR); - } - else - { - props.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR); - } - - // perform the checkin - property.getVersionOperationsService().checkin(node.getNodeRef(), - props, contentUrl, property.getKeepCheckedOut()); - return null; - } - }; - txnHelper.doInTransaction(callback); - - outcome = AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME; - - if (property.isWorkflowAction() == false) - { - outcome = outcome + AlfrescoNavigationHandler.OUTCOME_SEPARATOR + "browse"; - } - - // clear action context - property.setDocument(null); - resetState(); - } - catch (Throwable err) - { - Utils.addErrorMessage(Application.getMessage( - FacesContext.getCurrentInstance(), MSG_ERROR_CHECKIN) + err.getMessage(), err); - ReportedException.throwIfNecessary(err); - } - } - else - { - logger.warn("WARNING: checkinFileOK called without a current Document!"); - } - - return outcome; - } - - /** - * Action called upon completion of the Update File page - */ - public String updateFileOK(final FacesContext context, String outcome) - { - - // NOTE: for update the document node _is_ the working document! - final Node node = property.getDocument(); - if (node != null && this.getFileName() != null) - { - try - { - RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(FacesContext.getCurrentInstance()); - RetryingTransactionCallback callback = new RetryingTransactionCallback() - { - public Object execute() throws Throwable - { - if (logger.isDebugEnabled()) - logger.debug("Trying to update content node Id: " + node.getId()); - - // get an updating writer that we can use to modify the content on the current node - ContentWriter writer = property.getContentService().getWriter(node.getNodeRef(), ContentModel.PROP_CONTENT, true); - - // also update the mime type in case a different type of file is uploaded - String mimeType = Repository.getMimeTypeForFileName(context, property.getFileName()); - writer.setMimetype(mimeType); - - writer.putContent(property.getFile()); - return null; - } - }; - txnHelper.doInTransaction(callback); - - // clear action context - property.setDocument(null); - resetState(); - - outcome = AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME; - } - catch (Throwable err) - { - Utils.addErrorMessage(Application.getMessage( - FacesContext.getCurrentInstance(), MSG_ERROR_UPDATE) + err.getMessage(), err); - ReportedException.throwIfNecessary(err); - } - } - else - { - logger.warn("WARNING: updateFileOK called without a current Document!"); - } - - return outcome; - } - - /** - * Deals with the cancel button being pressed on the check in file page - */ - public String cancel() - { - String outcome = getDefaultCancelOutcome(); - - FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove(AlfrescoNavigationHandler.EXTERNAL_CONTAINER_SESSION); - - // reset the state - resetState(); - return outcome; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - - return null; - } - - /** - * Clear form state and upload file bean - */ - public void resetState() - { - // delete the temporary file we uploaded earlier - if (property.getFile() != null) - { - property.getFile().delete(); - } - - property.setFile(null); - property.setFileName(null); - property.setKeepCheckedOut(false); - property.setMinorChange(true); - property.setCopyLocation(CCProperties.COPYLOCATION_CURRENT); - property.setVersionNotes(""); - property.setSelectedSpaceId(null); - property.setWorkflowAction(false); - property.setWorkflowTaskId(null); - - // remove the file upload bean from the session - FacesContext ctx = FacesContext.getCurrentInstance(); - ctx.getExternalContext().getSessionMap().remove(FileUploadBean.FILE_UPLOAD_BEAN_NAME); - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/bean/coci/DoneEditingDialog.java b/war/src/main/java/org/alfresco/web/bean/coci/DoneEditingDialog.java deleted file mode 100644 index 5cab2ba653..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/coci/DoneEditingDialog.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.coci; - -import java.util.StringTokenizer; - -import javax.faces.application.NavigationHandler; -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.version.Version; -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.ui.common.Utils; - -/** - * This bean class handle done-editing(commit) dialog. - * - */ -public class DoneEditingDialog extends CheckinCheckoutDialog -{ - private final static String MSG_OK = "ok"; - private static final String MSG_DONE_EDITING = "done_editing"; - private final static String MSG_MISSING_ORIGINAL_NODE = "missing_original_node"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - private final static String DIALOG_NAME = AlfrescoNavigationHandler.DIALOG_PREFIX + "doneEditingFile"; - - - /** - * this flag indicates occurrence when source node isn't versionable, but working copy yet is versionable - */ - private boolean sourceVersionable; - - /** - * this field contains reference to source node for working copy - */ - private NodeRef sourceNodeRef; - - /** - * @return Returns label for new version with major changes - */ - public String getMajorNewVersionLabel() - { - String label = getCurrentVersionLabel(); - StringTokenizer st = new StringTokenizer(label, "."); - return (Integer.valueOf(st.nextToken()) + 1) + ".0"; - } - - /** - * @return Returns label for new version with minor changes - */ - public String getMinorNewVersionLabel() - { - String label = getCurrentVersionLabel(); - StringTokenizer st = new StringTokenizer(label, "."); - return st.nextToken() + "." + (Integer.valueOf(st.nextToken()) + 1); - } - - /** - * @return Returns flag, which indicates occurrence when source node is versionable - */ - public boolean isSourceVersionable() - { - return sourceVersionable; - } - - /** - * @return Returns true if source node for selected working copy founded - */ - public boolean isSourceFound() - { - return (sourceNodeRef != null); - } - - /** - * Method for handling done-editing action(e.g. "done_editing_doc") - * @param event Action Event - */ - public void handle(ActionEvent event) - { - setupContentAction(event); - - FacesContext fc = FacesContext.getCurrentInstance(); - NavigationHandler nh = fc.getApplication().getNavigationHandler(); - // if content is versionable then check-in else move to dialog for filling version info - if (isVersionable()) - { - nh.handleNavigation(fc, null, DIALOG_NAME); - } - else - { - checkinFileOK(fc, null); - nh.handleNavigation(fc, null, AlfrescoNavigationHandler.DIALOG_PREFIX + "browse"); - } - } - - @Override - public void setupContentAction(ActionEvent event) - { - super.setupContentAction(event); - - Node node = property.getDocument(); - if (node != null) - { - sourceNodeRef = getSourceNodeRef(node.getNodeRef()); - if (sourceNodeRef != null) - { - sourceVersionable = getNodeService().hasAspect(sourceNodeRef, ContentModel.ASPECT_VERSIONABLE); - } - } - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_OK); - } - - @Override - public boolean getFinishButtonDisabled() - { - return !isSourceFound(); - } - - @Override - public String getContainerTitle() - { - if (isSourceFound()) - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_DONE_EDITING) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) - + getNodeService().getProperty(sourceNodeRef, ContentModel.PROP_NAME) + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - else - { - String message = Application.getMessage(FacesContext.getCurrentInstance(), MSG_MISSING_ORIGINAL_NODE); - Utils.addErrorMessage(message); - return message; - } - } - - @Override - public void resetState() - { - super.resetState(); - - sourceVersionable = false; - sourceNodeRef = null; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return checkinFileOK(context, outcome); - } - - /** - * @return Returns version label for source node for working copy. Null indicates error - */ - private String getCurrentVersionLabel() - { - if (isSourceFound()) - { - Version curVersion = property.getVersionQueryService().getCurrentVersion(sourceNodeRef); - return curVersion.getVersionLabel(); - } - - return null; - } - - /** - * @param workingCopyNodeRef node reference to working copy - * @return Returns node reference to node, which is source for working copy node. Null indicates error - */ - private NodeRef getSourceNodeRef(NodeRef workingCopyNodeRef) - { - return getCheckOutCheckInService().getCheckedOut(workingCopyNodeRef); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/coci/EditOfflineDialog.java b/war/src/main/java/org/alfresco/web/bean/coci/EditOfflineDialog.java deleted file mode 100644 index c7aabb2c3c..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/coci/EditOfflineDialog.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ - -package org.alfresco.web.bean.coci; - -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.web.scripts.FileTypeImageUtils; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.servlet.DownloadContentServlet; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.users.UserPreferencesBean; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class EditOfflineDialog extends CheckinCheckoutDialog -{ - private static final long serialVersionUID = -4848508258494238150L; - - public static final String OFFLINE_EDITING = "offlineEditing"; - public static final String CLOSE = "close"; - public static final String MSG_ERROR_CHECKOUT = "error_checkout"; - public static final String OFFLINE_TITLE = "offline_title"; - - private static Log logger = LogFactory.getLog(EditOfflineDialog.class); - - private boolean continueCountdown; - protected UserPreferencesBean userPreferencesBean; - - @Override - public void init(Map parameters) - { - super.init(parameters); - continueCountdown = true; - } - - @Override - public void restored() - { - super.restored(); - continueCountdown = false; - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - String pattern = Application.getMessage(fc, OFFLINE_TITLE); - return MessageFormat.format(pattern, property.getDocument().getName()); - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return outcome; - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), CLOSE); - } - - /** - * Action listener for handle offline editing action. E.g "edit_doc_offline" - * action - * - * @param event ActionEvent - */ - public void setupContentAction(ActionEvent event) - { - UIActionLink link = (UIActionLink) event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - super.setupContentDocument(id); - checkoutFile(property.getDocument()); - if (userPreferencesBean.isDownloadAutomatically()) - { - FacesContext fc = FacesContext.getCurrentInstance(); - this.navigator.setupDispatchContext(property.getDocument()); - fc.getApplication().getNavigationHandler().handleNavigation(fc, null, - "dialog:editOfflineDialog"); - } - else - { - FacesContext fc = FacesContext.getCurrentInstance(); - fc.getApplication().getNavigationHandler().handleNavigation(fc, null, - "dialog:close:browse"); - } - } - else - { - property.setDocument(null); - } - super.resetState(); - } - - /** - * Checkout document to the same space as original one and then add the - * OFFLINE_EDITING property. - */ - private void checkoutFile(Node node) - { - UserTransaction tx = null; - FacesContext context = FacesContext.getCurrentInstance(); - - if (node != null) - { - try - { - tx = Repository.getUserTransaction(context, false); - tx.begin(); - - if (logger.isDebugEnabled()) - logger.debug("Trying to checkout content node Id: " + node.getId()); - NodeRef workingCopyRef = null; - - // checkout the content to the current space - workingCopyRef = property.getVersionOperationsService().checkout(node.getNodeRef()); - getNodeService().setProperty(workingCopyRef, ContentModel.PROP_WORKING_COPY_MODE, - OFFLINE_EDITING); - - // set the working copy Node instance - Node workingCopy = new Node(workingCopyRef); - property.setWorkingDocument(workingCopy); - - // create content URL to the content download servlet with ID and - // expected filename - String url = DownloadContentServlet.generateDownloadURL(workingCopyRef, workingCopy - .getName()); - - workingCopy.getProperties().put("url", url); - workingCopy.getProperties().put("fileType32", - FileTypeImageUtils.getFileTypeImage(workingCopy.getName(), false)); - - // commit the transaction - tx.commit(); - } - catch (Throwable err) - { - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - - Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), - MSG_ERROR_CHECKOUT) - + err.getMessage(), err); - } - } - else - { - logger.warn("WARNING: checkoutFile called without a current Document!"); - } - } - - @Override - public String cancel() - { - super.cancel(); - return "dialog:close:browse"; - } - - /** - * @return userPreferencesBean bean with current user's preferences - */ - public UserPreferencesBean getUserPreferencesBean() - { - return userPreferencesBean; - } - - /** - * @param userPreferencesBean bean with current user's preferences to set - */ - public void setUserPreferencesBean(UserPreferencesBean userPreferencesBean) - { - this.userPreferencesBean = userPreferencesBean; - } - - /** - * @return continueCountdown - */ - public boolean isContinueCountdown() - { - return continueCountdown; - } - - /** - * @param continueCountdown boolean - */ - public void setContinueCountdown(boolean continueCountdown) - { - this.continueCountdown = continueCountdown; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/coci/EditOnlineDialog.java b/war/src/main/java/org/alfresco/web/bean/coci/EditOnlineDialog.java deleted file mode 100644 index 78ce411465..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/coci/EditOnlineDialog.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.coci; - -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.service.cmr.repository.ContentReader; -import org.alfresco.service.cmr.rule.RuleType; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.springframework.extensions.webscripts.ui.common.StringUtils; - -/** - * This base dialog class provides methods for online editing. It does - * doesn't have entry in web-client-config-dialogs.xml as is not instantiated directly. - */ -public class EditOnlineDialog extends CCCheckoutFileDialog -{ - public final static String ONLINE_EDITING = "onlineEditing"; - - - /** - * Action listener for handle webdav online editing action. E.g "edit_doc_online_webdav" action - * - * @param event ActionEvent - */ - public void handleWebdavEditing(ActionEvent event) - { - handle(event); - - Node workingCopyNode = property.getDocument(); - if (workingCopyNode != null) - { - UIActionLink link = (UIActionLink) event.getComponent(); - Map params = link.getParameterMap(); - String webdavUrl = params.get("webdavUrl"); - - if (webdavUrl != null) - { - // modify webDav for editing working copy - property.setWebdavUrl(webdavUrl.substring(0, webdavUrl.lastIndexOf('/') + 1) + workingCopyNode.getName()); - } - - FacesContext fc = FacesContext.getCurrentInstance(); - - fc.getApplication().getNavigationHandler().handleNavigation(fc, null, "dialog:close:browse"); - } - } - - /** - * Action listener for handle cifs online editing action. E.g "edit_doc_online_cifs" action - * - * @param event ActionEvent - */ - public void handleCifsEditing(ActionEvent event) - { - handle(event); - - Node workingCopyNode = property.getDocument(); - if (workingCopyNode != null) - { - UIActionLink link = (UIActionLink) event.getComponent(); - Map params = link.getParameterMap(); - String cifsPath = params.get("cifsPath"); - - if (cifsPath != null) - { - // modify cifsPath for editing working copy - property.setCifsPath(cifsPath.substring(0, cifsPath.lastIndexOf('\\') + 1) + workingCopyNode.getName()); - } - - FacesContext fc = FacesContext.getCurrentInstance(); - - fc.getApplication().getNavigationHandler().handleNavigation(fc, null, "dialog:close:browse"); - } - } - - /** - * Action listener for handle http online(inline) editing action. E.g "edit_doc_online_http" action - * - * @param event ActionEvent - */ - public void handleHttpEditing(ActionEvent event) - { - handle(event); - - Node workingCopyNode = property.getDocument(); - if (workingCopyNode != null) - { - ContentReader reader = property.getContentService().getReader(workingCopyNode.getNodeRef(), ContentModel.PROP_CONTENT); - if (reader != null) - { - String mimetype = reader.getMimetype(); - - // calculate which editor screen to display - if (MimetypeMap.MIMETYPE_TEXT_PLAIN.equals(mimetype) || MimetypeMap.MIMETYPE_XML.equals(mimetype) || - MimetypeMap.MIMETYPE_TEXT_CSS.equals(mimetype) || MimetypeMap.MIMETYPE_JAVASCRIPT.equals(mimetype)) - { - // make content available to the text editing screen - property.setEditorOutput(reader.getContentString()); - - // navigate to appropriate screen - FacesContext fc = FacesContext.getCurrentInstance(); - fc.getApplication().getNavigationHandler().handleNavigation(fc, null, "dialog:close:browse"); - this.navigator.setupDispatchContext(workingCopyNode); - fc.getApplication().getNavigationHandler().handleNavigation(fc, null, "dialog:editTextInline"); - } - else - { - // make content available to the html editing screen - property.setDocumentContent(StringUtils.stripUnsafeHTMLTags(reader.getContentString(), false)); - property.setEditorOutput(null); - - // navigate to appropriate screen - FacesContext fc = FacesContext.getCurrentInstance(); - fc.getApplication().getNavigationHandler().handleNavigation(fc, null, "dialog:close:browse"); - this.navigator.setupDispatchContext(workingCopyNode); - fc.getApplication().getNavigationHandler().handleNavigation(fc, null, "dialog:editHtmlInline"); - } - } - } - } - - /** - * Base handling method. - * - * @param event ActionEvent - */ - public void handle(ActionEvent event) - { - super.setupContentAction(event); - - Node node = property.getDocument(); - if (node != null) - { - UserTransaction tx = null; - FacesContext context = FacesContext.getCurrentInstance(); - - try - { - tx = Repository.getUserTransaction(context, false); - tx.begin(); - - // if current content is already working copy then we don't checkout - if (node.hasAspect(ContentModel.ASPECT_WORKING_COPY) == false) - { - // if checkout is successful, then checkoutFile sets property workingDocument - checkoutFile(FacesContext.getCurrentInstance(), null); - - Node workingCopyNode = property.getWorkingDocument(); - - if (workingCopyNode != null) - { - getRuleService().disableRules(); - try - { - // set working copy node as document for editing - property.setDocument(workingCopyNode); - getNodeService().setProperty(workingCopyNode.getNodeRef(), ContentModel.PROP_WORKING_COPY_MODE, ONLINE_EDITING); - } - finally - { - getRuleService().enableRules(); - } - } - } - - // commit the transaction - tx.commit(); - } - catch (Throwable err) - { - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - property.setDocument(null); - } - } - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/bean/coci/UploadNewVersionDialog.java b/war/src/main/java/org/alfresco/web/bean/coci/UploadNewVersionDialog.java deleted file mode 100644 index 156437a08d..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/coci/UploadNewVersionDialog.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.coci; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.Application; - -/** - * Dialog supporting the Upload New Version action on a working copy node. - */ -public class UploadNewVersionDialog extends DoneEditingDialog -{ - private final static String MSG_UPLOAD_NEW_VERSION = "upload_new_version"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - private final static String MSG_OF = "of"; - - private boolean finishedEditing = false; - - public void setFinishedEditing(boolean finished) - { - this.finishedEditing = finished; - } - - public boolean isFinishedEditing() - { - return finishedEditing; - } - - @Override - public boolean getFinishButtonDisabled() - { - return property.getFile() == null; - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_UPLOAD_NEW_VERSION) + " " + Application.getMessage(fc, MSG_OF) + " " + - Application.getMessage(fc, MSG_LEFT_QUOTE) - + property.getDocument().getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - if (finishedEditing) - { - property.setKeepCheckedOut(false); - return checkinFileOK(context, outcome); - } - else - { - return updateFileOK(context, outcome); - } - } - - @Override - public void resetState() - { - super.resetState(); - finishedEditing = false; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/content/AddContentDialog.java b/war/src/main/java/org/alfresco/web/bean/content/AddContentDialog.java deleted file mode 100644 index 0467b6c4f9..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/content/AddContentDialog.java +++ /dev/null @@ -1,355 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.content; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.springframework.extensions.config.Config; -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigService; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.repo.content.filestore.FileContentReader; -import org.alfresco.service.cmr.model.FileExistsException; -import org.alfresco.service.cmr.repository.ContentReader; -import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.FileUploadBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.Utils; - -/** - * Bean implementation for the "Add Content" dialog - * - * @author gavinc - */ -public class AddContentDialog extends BaseContentWizard -{ - private final static String MSG_OK = "ok"; - private static final long serialVersionUID = 3593557546118692687L; - - protected List inlineEditableMimeTypes; - protected File file; - - // ------------------------------------------------------------------------------ - // Dialog implementation - - @Override - protected String finishImpl(FacesContext context, String outcome) - throws Exception - { - // Try and extract metadata from the file - ContentReader cr = new FileContentReader(this.file); - cr.setMimetype(this.mimeType); - cr.setEncoding(this.encoding); - // create properties for content type - Map contentProps = new HashMap(5, 1.0f); - - if (Repository.extractMetadata(FacesContext.getCurrentInstance(), cr, contentProps)) - { - this.author = (String)(contentProps.get(ContentModel.PROP_AUTHOR)); - this.title = DefaultTypeConverter.INSTANCE.convert(String.class, contentProps.get(ContentModel.PROP_TITLE)); - this.description = DefaultTypeConverter.INSTANCE.convert(String.class, contentProps.get(ContentModel.PROP_DESCRIPTION)); - } - - // default the title to the file name if not set - if (this.title == null) - { - this.title = this.fileName; - } - - // determine whether inline editing should be enabled by default. - // if the mime type of the added file is in the list of mime types - // configured in "Content Wizards" then enable inline editing - List mimeTypes = getInlineEditableMimeTypes(); - if (mimeTypes.contains(this.mimeType)) - { - this.inlineEdit = true; - } - - saveContent(this.file, null); - - // return default outcome - return outcome; - } - - @Override - public void init(Map parameters) - { - super.init(parameters); - - clearUpload(); - } - - @Override - protected String doPostCommitProcessing(FacesContext context, String outcome) - { - clearUpload(); - - // as we were successful, go to the set properties dialog if asked - // to otherwise just return - if (this.showOtherProperties) - { - // check whether the created node is checked out, if a 'check out' - // rule is present in the space the new node will be and an - // attempt to modify the properties will cause an error (ALF-438) - if (getNodeService().hasAspect(this.createdNode, ContentModel.ASPECT_LOCKABLE)) - { - Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), MSG_NODE_LOCKED)); - return outcome; - } - else - { - // we are going to immediately edit the properties so we need - // to setup the BrowseBean context appropriately - this.browseBean.setDocument(new Node(this.createdNode)); - - return "dialog:setContentProperties"; - } - } - else - { - return outcome; - } - } - - @Override - protected String getDefaultFinishOutcome() - { - // as we are using this dialog outside the dialog framework - // just go back to the main page - - return "dialog:close:browse"; - } - - // ------------------------------------------------------------------------------ - // Bean getters and setters - - /** - * @return Returns the message to display when a file has been uploaded - */ - public String getFileUploadSuccessMsg() - { - // NOTE: This is a far from ideal solution but will do until we have - // a pure JSF upload solution working. This method is only called - // after a file is uploaded, so we can calculate the mime type and - // determine whether to enable inline editing in here. - FacesContext fc = FacesContext.getCurrentInstance(); - - // Identify the mimetype as best as we can - this.mimeType = Repository.getMimeTypeForFile(fc, this.fileName, this.file); - - // Identify the encoding as best we can (only really important for text based formats) - this.encoding = "UTF-8"; - InputStream is = null; - try - { - if (this.file != null) - { - is = new BufferedInputStream(new FileInputStream(this.file)); - this.encoding = Repository.guessEncoding(fc, is, this.mimeType); - } - } - catch (Throwable e) - { - // Not terminal - logger.error("Failed to get encoding from file: " + this.fileName, e); - } - finally - { - try { is.close(); } catch (Throwable e) {} // Includes NPE - } - - // Offer inline editing for HTML only - this.inlineEdit = (this.mimeType.equals(MimetypeMap.MIMETYPE_HTML)); - - // get the file upload message - String msg = Application.getMessage(FacesContext.getCurrentInstance(), "file_upload_success"); - return MessageFormat.format(msg, new Object[] {Utils.encode(getFileName())}); - } - - /** - * @return Returns the name of the file - */ - public String getFileName() - { - // try and retrieve the file and filename from the file upload bean - // representing the file we previously uploaded. - FacesContext ctx = FacesContext.getCurrentInstance(); - FileUploadBean fileBean = (FileUploadBean)ctx.getExternalContext().getSessionMap(). - get(FileUploadBean.FILE_UPLOAD_BEAN_NAME); - if (fileBean != null) - { - this.file = fileBean.getFile(); - this.fileName = fileBean.getFileName(); - } - - return this.fileName; - } - - /** - * @param fileName The name of the file - */ - public void setFileName(String fileName) - { - this.fileName = fileName; - - // we also need to keep the file upload bean in sync - FacesContext ctx = FacesContext.getCurrentInstance(); - FileUploadBean fileBean = (FileUploadBean)ctx.getExternalContext().getSessionMap(). - get(FileUploadBean.FILE_UPLOAD_BEAN_NAME); - if (fileBean != null) - { - fileBean.setFileName(this.fileName); - } - } - - // ------------------------------------------------------------------------------ - // Action event handlers - - /** - * Action listener called when the add content dialog is called - */ - public void start(ActionEvent event) - { - // NOTE: this is a temporary solution to allow us to use the new dialog - // framework beans outside of the dialog framework, we need to do - // this because the uploading requires a separate non-JSF form, this - // approach can not be used in the current dialog framework. Until - // we have a pure JSF upload solution we need this initialisation - - init(null); - } - - /** - * Action handler called when the user wishes to remove an uploaded file - */ - public String removeUploadedFile() - { - clearUpload(); - - // also clear the file name - this.fileName = null; - - // refresh the current page - return null; - } - - /** - * Action handler called when the dialog is cancelled - */ - public String cancel() - { - clearUpload(); - return "dialog:close"; - } - - // ------------------------------------------------------------------------------ - // Helper Methods - - /** - * Deletes the uploaded file and removes the FileUploadBean from the session - */ - protected void clearUpload() - { - // delete the temporary file we uploaded earlier - if (this.file != null) - { - this.file.delete(); - } - - this.file = null; - - // remove the file upload bean from the session - FacesContext ctx = FacesContext.getCurrentInstance(); - ctx.getExternalContext().getSessionMap().remove(FileUploadBean.FILE_UPLOAD_BEAN_NAME); - } - - protected List getInlineEditableMimeTypes() - { - if ((this.inlineEditableMimeTypes == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - this.inlineEditableMimeTypes = new ArrayList(8); - - // get the create mime types list from the config - ConfigService svc = Application.getConfigService(FacesContext.getCurrentInstance()); - Config wizardCfg = svc.getConfig("Content Wizards"); - if (wizardCfg != null) - { - ConfigElement typesCfg = wizardCfg.getConfigElement("create-mime-types"); - if (typesCfg != null) - { - for (ConfigElement child : typesCfg.getChildren()) - { - String currentMimeType = child.getAttribute("name"); - this.inlineEditableMimeTypes.add(currentMimeType); - } - } - } - } - - return this.inlineEditableMimeTypes; - } - - @Override - public String getFinishButtonLabel() - { - - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_OK); - } - - @Override - protected String formatErrorMessage(Throwable exception) - { - if (exception instanceof FileExistsException) - { - return MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_EXISTS), - ((FileExistsException)exception).getName()); - } - else - { - return MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), "error_content"), - exception.getMessage()); - } - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/content/BaseContentWizard.java b/war/src/main/java/org/alfresco/web/bean/content/BaseContentWizard.java deleted file mode 100644 index 67a305b8ba..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/content/BaseContentWizard.java +++ /dev/null @@ -1,623 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.content; - -import java.io.File; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.model.SelectItem; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.dictionary.TypeDefinition; -import org.alfresco.service.cmr.repository.ContentService; -import org.alfresco.service.cmr.repository.ContentWriter; -import org.alfresco.service.cmr.repository.MimetypeService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.service.transaction.TransactionService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.wizard.BaseWizardBean; -import org.alfresco.web.data.IDataContainer; -import org.alfresco.web.data.QuickSort; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.repo.component.UICharsetSelector; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.extensions.config.Config; -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigService; - -/** - * Base class for the content related wizards and dialogs - * - * @author gavinc - */ -@SuppressWarnings("serial") -public abstract class BaseContentWizard extends BaseWizardBean -{ - protected String fileName; - protected String author; - protected String title; - protected String description; - protected String mimeType; - protected String encoding; - protected String objectType; - protected boolean inlineEdit; - protected boolean otherPropertiesChoiceVisible = true; - protected boolean showOtherProperties = true; - - // the NodeRef of the node created during finish - protected NodeRef createdNode; - protected List objectTypes; - transient private ContentService contentService; - transient private TransactionService transactionService; - - protected static final String MSG_NODE_LOCKED = "node_locked_dialog_closed"; - - protected static Log logger = LogFactory.getLog(BaseContentWizard.class); - - - // ------------------------------------------------------------------------------ - // Wizard implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - this.fileName = null; - this.author = null; - this.title = null; - this.description = null; - this.mimeType = null; - this.inlineEdit = false; - this.objectType = null; - - initOtherProperties(); - } - - @Override - public boolean getFinishButtonDisabled() - { - return (this.fileName == null || - this.fileName.length() == 0 || - this.mimeType == null); - } - - - // ------------------------------------------------------------------------------ - // Bean Getters and Setters - - /** - * @return Returns the name of the file - */ - public String getFileName() - { - return this.fileName; - } - - /** - * @param fileName The name of the file - */ - public void setFileName(String fileName) - { - this.fileName = fileName; - } - - /** - * @return Returns the author - */ - public String getAuthor() - { - return this.author; - } - - /** - * @param author Sets the author - */ - public void setAuthor(String author) - { - this.author = author; - } - - /** - * @return Returns the mime type currenty selected - */ - public String getMimeType() - { - return this.mimeType; - } - - /** - * @param mimeType Sets the currently selected mime type - */ - public void setMimeType(String mimeType) - { - this.mimeType = mimeType; - } - - /** - * @return Returns the encoding currently selected - */ - public String getEncoding() - { - if (encoding == null) - { - ConfigService configSvc = Application.getConfigService(FacesContext.getCurrentInstance()); - Config config = configSvc.getConfig("Content Wizards"); - if (config != null) - { - ConfigElement defaultEncCfg = config.getConfigElement("default-encoding"); - if (defaultEncCfg != null) - { - String value = defaultEncCfg.getValue(); - if (value != null) - { - encoding = value.trim(); - } - } - } - if (encoding == null || encoding.length() == 0) - { - // if not configured, set to a sensible default for most character sets - encoding = "UTF-8"; - } - } - return encoding; - } - - /** - * @param encoding the document's encoding - */ - public void setEncoding(String encoding) - { - this.encoding = encoding; - } - - /** - * @return Returns the object type currenty selected - */ - public String getObjectType() - { - return this.objectType; - } - - /** - * @param objectType Sets the currently selected object type - */ - public void setObjectType(String objectType) - { - this.objectType = objectType; - } - - /** - * @return Returns the description - */ - public String getDescription() - { - return this.description; - } - - /** - * @param description Sets the description - */ - public void setDescription(String description) - { - this.description = description; - } - - /** - * @return Returns the title - */ - public String getTitle() - { - return this.title; - } - - /** - * @param title Sets the title - */ - public void setTitle(String title) - { - this.title = title; - } - - /** - * @return Returns the inline edit flag. - */ - public boolean isInlineEdit() - { - return this.inlineEdit; - } - - /** - * @param inlineEdit The inline edit flag to set. - */ - public void setInlineEdit(boolean inlineEdit) - { - this.inlineEdit = inlineEdit; - } - - /** - * @return Determines whether the choice to modify all properties - * is shown - */ - public boolean getOtherPropertiesChoiceVisible() - { - return this.otherPropertiesChoiceVisible; - } - - /** - * @return Determines whether the edit properties dialog should be - * shown when this one ends - */ - public boolean getShowOtherProperties() - { - return this.showOtherProperties; - } - - /** - * @param showOthers Sets whether the edit properties dialog is shown - */ - public void setShowOtherProperties(boolean showOthers) - { - this.showOtherProperties = showOthers; - } - - public List getEncodings() - { - return UICharsetSelector.getCharsetEncodingList(); - } - - /** - * @return Returns a list of object types to allow the user to select from - */ - public List getObjectTypes() - { - return getTransactionService().getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback>() - { - @Override - public List execute() throws Throwable - { - return getObjectTypesImpl(); - } - }, true); - } - - private List getObjectTypesImpl() - { - if ((this.objectTypes == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - FacesContext context = FacesContext.getCurrentInstance(); - - // add the well known object type to start with - this.objectTypes = new ArrayList(5); - - ConfigService svc = Application.getConfigService(FacesContext.getCurrentInstance()); - Config wizardCfg = svc.getConfig("Content Wizards"); - if (wizardCfg != null) - { - ConfigElement defaultTypesCfg = wizardCfg.getConfigElement("default-content-type"); - String parentLabel = ""; - if (defaultTypesCfg != null) - { - // Get the default content-type to apply - ConfigElement typeElement = defaultTypesCfg.getChildren().get(0); - QName parentQName = Repository.resolveToQName(typeElement.getAttribute("name")); - TypeDefinition parentType = null; - if (parentQName != null) - { - parentType = this.getDictionaryService().getType(parentQName); - - if (parentType == null) - { - // If no default content type is defined default to content - parentQName = ContentModel.TYPE_CONTENT; - parentType = this.getDictionaryService().getType(ContentModel.TYPE_CONTENT); - this.objectTypes.add(new SelectItem(ContentModel.TYPE_CONTENT.toString(), - Application.getMessage(context, "content"))); - logger.warn("Configured default content type not found in dictionary: " + parentQName); - } - else - { - // try and get the display label from config - parentLabel = Utils.getDisplayLabel(context, typeElement); - - // if there wasn't a client based label try and get it from the dictionary - if (parentLabel == null) - { - parentLabel = parentType.getTitle(this.getDictionaryService()); - } - - // finally, just use the localname - if (parentLabel == null) - { - parentLabel = parentQName.getLocalName(); - } - } - } - - // Get all content types defined - ConfigElement typesCfg = wizardCfg.getConfigElement("content-types"); - if (typesCfg != null) - { - for (ConfigElement child : typesCfg.getChildren()) - { - QName idQName = Repository.resolveToQName(child.getAttribute("name")); - if (idQName != null) - { - TypeDefinition typeDef = this.getDictionaryService().getType(idQName); - - if (typeDef != null) - { - // for each type check if it is a subtype of the default content type - if (this.getDictionaryService().isSubClass(typeDef.getName(), parentType.getName())) - { - // try and get the display label from config - String label = Utils.getDisplayLabel(context, child); - - // if there wasn't a client based label try and get it from the dictionary - if (label == null) - { - label = typeDef.getTitle(this.getDictionaryService()); - } - - // finally, just use the localname - if (label == null) - { - label = idQName.getLocalName(); - } - - this.objectTypes.add(new SelectItem(idQName.toString(), label)); - } - else - { - logger.warn("Failed to add '" + child.getAttribute("name") + - "' to the list of content types - it is not a subtype of " + parentQName); - } - } - } - else - { - logger.warn("Failed to add '" + child.getAttribute("name") + - "' to the list of content types as the type is not recognised"); - } - } - } - - // Case when no type is defined - we add the default content type to the list of available types - if (this.objectTypes.isEmpty()) - { - // add default content type to the list of available types - this.objectTypes.add(new SelectItem(parentQName.toString(), parentLabel)); - } - - // make sure the list is sorted by the label - QuickSort sorter = new QuickSort(this.objectTypes, "label", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - } - else - { - logger.warn("Could not find 'content-types' configuration element"); - } - } - else - { - logger.warn("Could not find 'Content Wizards' configuration section"); - } - - } - - return this.objectTypes; - } - - - // ------------------------------------------------------------------------------ - // Service Injection - - /** - * @param contentService The contentService to set. - */ - public void setContentService(ContentService contentService) - { - this.contentService = contentService; - } - - protected ContentService getContentService() - { - if (contentService == null) - { - contentService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getContentService(); - } - return contentService; - } - - protected TransactionService getTransactionService() - { - if (null == transactionService) - { - transactionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getTransactionService(); - } - - return transactionService; - } - - - // ------------------------------------------------------------------------------ - // Helper methods - - /** - * Save the specified content using the currently set wizard attributes - * - * @param fileContent File content to save - * @param strContent String content to save - */ - protected void saveContent(File fileContent, String strContent) throws Exception - { - // get the node ref of the node that will contain the content - NodeRef containerNodeRef; - String nodeId = this.navigator.getCurrentNodeId(); - if (nodeId == null) - { - containerNodeRef = this.getNodeService().getRootNode(Repository.getStoreRef()); - } - else - { - containerNodeRef = new NodeRef(Repository.getStoreRef(), nodeId); - } - - // apply the inline editable aspect (by adding the property at create time) - Map editProps = new HashMap(6); - if (this.inlineEdit == true) - { - editProps.put(ApplicationModel.PROP_EDITINLINE, this.inlineEdit); - if (logger.isDebugEnabled()) - logger.debug("Added inlineeditable aspect with properties: " + editProps); - } - - // set the name - editProps.put(ContentModel.PROP_NAME, this.fileName); - - // set the author property - editProps.put(ContentModel.PROP_AUTHOR, this.author); - - // apply the titled aspect - title and description - editProps.put(ContentModel.PROP_TITLE, this.title); - editProps.put(ContentModel.PROP_DESCRIPTION, this.description); - if (logger.isDebugEnabled()) - logger.debug("Added titled aspect with properties: " + this.title + ", " + this.description); - - // create the node - NodeRef fileNodeRef = this.getNodeService().createNode( - containerNodeRef, - ContentModel.ASSOC_CONTAINS, - QName.createQNameWithValidLocalName(NamespaceService.CONTENT_MODEL_1_0_URI, this.fileName), - Repository.resolveToQName(this.objectType), - editProps).getChildRef(); - - if (logger.isDebugEnabled()) - logger.debug("Created file node for file: " + this.fileName); - - // get a writer for the content and put the file - ContentWriter writer = getContentService().getWriter(fileNodeRef, ContentModel.PROP_CONTENT, true); - // set the mimetype and encoding - writer.setMimetype(this.mimeType); - writer.setEncoding(getEncoding()); - if (fileContent != null) - { - writer.putContent(fileContent); - } - else - { - writer.putContent(strContent == null ? "" : strContent); - } - - // remember the created node now - this.createdNode = fileNodeRef; - } - - /** - * Returns the display label for the mime type currently chosen - * - * @param mimeType The mime type to get the display label of - * @return The human readable version of the content type - */ - protected String getSummaryMimeType(String mimeType) - { - ServiceRegistry registry = Repository.getServiceRegistry(FacesContext.getCurrentInstance()); - MimetypeService mimetypeService = registry.getMimetypeService(); - - // get the mime type display name - Map mimeTypes = mimetypeService.getDisplaysByMimetype(); - return mimeTypes.get(mimeType); - } - - /** - * Returns the display label for the currently selected object type - * - * @return The objevt type label - */ - protected String getSummaryObjectType() - { - String objType = null; - - for (SelectItem item : this.getObjectTypes()) - { - if (item.getValue().equals(this.objectType)) - { - objType = item.getLabel(); - break; - } - } - - return objType; - } - - /** - * Initialises the other properties flags from config - */ - protected void initOtherProperties() - { - // TODO - review implications of these default values for dynamic/MT client - ConfigService configSvc = Application.getConfigService(FacesContext.getCurrentInstance()); - - if (configSvc != null) - { - Config config = configSvc.getConfig("Content Wizards"); - if (config != null) - { - ConfigElement otherPropsCfg = config.getConfigElement("other-properties"); - if (otherPropsCfg != null) - { - // get the attributes - String userChoiceVisible = otherPropsCfg.getAttribute("user-choice-visible"); - String userChoiceDefault = otherPropsCfg.getAttribute("user-choice-default"); - - // set the defaults - if (userChoiceVisible != null) - { - this.otherPropertiesChoiceVisible = Boolean.parseBoolean(userChoiceVisible); - } - - if (userChoiceDefault != null) - { - this.showOtherProperties = Boolean.parseBoolean(userChoiceDefault); - } - } - } - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/content/CreateContentWizard.java b/war/src/main/java/org/alfresco/web/bean/content/CreateContentWizard.java deleted file mode 100644 index 00ac0c5b40..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/content/CreateContentWizard.java +++ /dev/null @@ -1,285 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.content; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.ResourceBundle; - -import javax.faces.context.FacesContext; -import javax.faces.event.ValueChangeEvent; -import javax.faces.model.SelectItem; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.service.cmr.model.FileExistsException; -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.data.IDataContainer; -import org.alfresco.web.data.QuickSort; -import org.alfresco.web.ui.common.Utils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.extensions.config.Config; -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigService; - -/** - * Bean implementation for the "Create Content Wizard" dialog - * - * @author gavinc - */ -public class CreateContentWizard extends BaseContentWizard -{ - private static final long serialVersionUID = -2740634368271194418L; - - protected String content = null; - protected List createMimeTypes; - - private static Log logger = LogFactory.getLog(CreateContentWizard.class); - - - // ------------------------------------------------------------------------------ - // Wizard implementation - - - @Override - public String finish() - { - String result = super.finish(); - - return result; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) - throws Exception - { - saveContent(null, this.content); - - // return the default outcome - return outcome; - } - - @Override - public void init(Map parameters) - { - super.init(parameters); - - this.content = null; - this.inlineEdit = true; - this.mimeType = MimetypeMap.MIMETYPE_HTML; - } - - @Override - public boolean getNextButtonDisabled() - { - // TODO: Allow the next button state to be configured so that - // wizard implementations don't have to worry about - // checking step numbers - - boolean disabled = false; - int step = Application.getWizardManager().getCurrentStep(); - switch(step) - { - case 1: - { - disabled = (this.fileName == null || this.fileName.length() == 0); - break; - } - } - - return disabled; - } - - - @Override - public boolean getFinishButtonDisabled() - { - boolean disabled = false; - int step = Application.getWizardManager().getCurrentStep(); - switch(step) - { - case 1: - { - disabled = (this.fileName == null || this.fileName.length() == 0); - break; - } - } - - return disabled; - } - - @Override - protected String doPostCommitProcessing(FacesContext context, String outcome) - { - // as we were successful, go to the set properties dialog if asked - // to otherwise just return - if (this.showOtherProperties) - { - // check whether the created node is checked out, if a 'check out' - // rule is present in the space the new node will be and an - // attempt to modify the properties will cause an error (ALF-438) - if (getNodeService().hasAspect(this.createdNode, ContentModel.ASPECT_LOCKABLE)) - { - Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), MSG_NODE_LOCKED)); - return outcome; - } - else - { - // we are going to immediately edit the properties so we need - // to setup the BrowseBean context appropriately - this.browseBean.setDocument(new Node(this.createdNode)); - - return getDefaultFinishOutcome() + AlfrescoNavigationHandler.OUTCOME_SEPARATOR + - "dialog:setContentProperties"; - } - } - else - { - return outcome; - } - } - - // ------------------------------------------------------------------------------ - // Bean Getters and Setters - - /** - * @return Returns the content from the edited form. - */ - public String getContent() - { - return this.content; - } - - /** - * @param content The content to edit (should be clear initially) - */ - public void setContent(String content) - { - this.content = content; - } - - /** - * @return Returns a list of mime types to allow the user to select from - */ - public List getCreateMimeTypes() - { - if ((this.createMimeTypes == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - FacesContext context = FacesContext.getCurrentInstance(); - - // add the well known object type to start with - this.createMimeTypes = new ArrayList(5); - - // add the configured create mime types to the list - ConfigService svc = Application.getConfigService(context); - Config wizardCfg = svc.getConfig("Content Wizards"); - if (wizardCfg != null) - { - ConfigElement typesCfg = wizardCfg.getConfigElement("create-mime-types"); - if (typesCfg != null) - { - for (ConfigElement child : typesCfg.getChildren()) - { - String currentMimeType = child.getAttribute("name"); - if (currentMimeType != null) - { - String label = getSummaryMimeType(currentMimeType); - this.createMimeTypes.add(new SelectItem(currentMimeType, label)); - } - } - - // make sure the list is sorted by the label - QuickSort sorter = new QuickSort(this.objectTypes, "label", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - } - else - { - logger.warn("Could not find 'create-mime-types' configuration element"); - } - } - else - { - logger.warn("Could not find 'Content Wizards' configuration section"); - } - - } - - return this.createMimeTypes; - } - - /** - * @return Returns the summary data for the wizard. - */ - public String getSummary() - { - ResourceBundle bundle = Application.getBundle(FacesContext.getCurrentInstance()); - - // TODO: show first few lines of content here? - return buildSummary( - new String[] {bundle.getString("file_name"), - bundle.getString("type"), - bundle.getString("content_type")}, - new String[] {Utils.encode(this.fileName), getSummaryObjectType(), - getSummaryMimeType(this.mimeType)}); - } - - - // ------------------------------------------------------------------------------ - // Action event handlers - - /** - * Create content type value changed by the user - */ - public void createContentChanged(ValueChangeEvent event) - { - // clear the content as HTML is not compatible with the plain text box etc. - this.content = null; - } - - @Override - protected String formatErrorMessage(Throwable exception) - { - if (exception instanceof FileExistsException) - { - return MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_EXISTS), - ((FileExistsException)exception).getName()); - } - else - { - return MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), "error_content"), - exception.getMessage()); - } - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/content/DeleteContentAssociationDialog.java b/war/src/main/java/org/alfresco/web/bean/content/DeleteContentAssociationDialog.java deleted file mode 100644 index ef2b119988..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/content/DeleteContentAssociationDialog.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.content; - -import java.text.MessageFormat; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean implementation for the "Delete Content Association" dialog - * - * @author valerysh - * @author gavinc - */ -public class DeleteContentAssociationDialog extends DeleteContentDialog -{ - - private static final Log logger = LogFactory.getLog(DeleteContentAssociationDialog.class); - - // ------------------------------------------------------------------------------ - // Dialog implementation - - @Override - protected String finishImpl(FacesContext context, String outcome) - throws Exception - { - // get the content to delete - Node node = this.browseBean.getDocument(); - - if (node != null) - { - if (logger.isDebugEnabled()) - logger.debug("Trying to delete content node association: " + node.getId()); - - NodeRef parentRef = this.navigator.getCurrentNode().getNodeRef(); - QName qname = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, - QName.createValidLocalName(node.getName())); - ChildAssociationRef childAssocRef = new ChildAssociationRef(ContentModel.ASSOC_CONTAINS, - parentRef, qname, node.getNodeRef()); - - // remove the child association - this.getNodeService().removeChildAssociation(childAssocRef); - } - else - { - logger.warn("WARNING: delete called without a current Document!"); - } - - return outcome; - } - - // ------------------------------------------------------------------------------ - // Bean Getters and Setters - - /** - * Returns the confirmation to display to the user before deleting the content. - * - * @return The formatted message to display - */ - public String getConfirmMessage() - { - String fileConfirmMsg = null; - - Node document = this.browseBean.getDocument(); - - fileConfirmMsg = Application.getMessage(FacesContext.getCurrentInstance(), - "delete_file_assoc_confirm"); - - return MessageFormat.format(fileConfirmMsg, - new Object[] {document.getName()}); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/content/DeleteContentDialog.java b/war/src/main/java/org/alfresco/web/bean/content/DeleteContentDialog.java deleted file mode 100644 index 89b4b510ff..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/content/DeleteContentDialog.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.content; - -import java.text.MessageFormat; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.ml.MultilingualContentService; -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean implementation for the "Delete Content" dialog - * - * @author gavinc - */ -public class DeleteContentDialog extends BaseDialogBean -{ - private static final long serialVersionUID = 4199496011879649213L; - - transient private MultilingualContentService multilingualContentService; - - private static final Log logger = LogFactory.getLog(DeleteContentDialog.class); - - // ------------------------------------------------------------------------------ - // Dialog implementation - - @Override - protected String finishImpl(FacesContext context, String outcome) - throws Exception - { - // get the content to delete - Node node = this.browseBean.getDocument(); - if (node != null) - { - if(ContentModel.TYPE_MULTILINGUAL_CONTAINER.equals(node.getType())) - { - if (logger.isDebugEnabled()) - logger.debug("Trying to delete multilingual container: " + node.getId() + " and its translations" ); - - // delete the mlContainer and its translations - getMultilingualContentService().deleteTranslationContainer(node.getNodeRef()); - } - else - { - if (logger.isDebugEnabled()) - logger.debug("Trying to delete content node: " + node.getId()); - - // delete the node - this.getNodeService().deleteNode(node.getNodeRef()); - } - - } - else - { - logger.warn("WARNING: delete called without a current Document!"); - } - - return outcome; - } - - @Override - protected String doPostCommitProcessing(FacesContext context, String outcome) - { - // clear action context - this.browseBean.setDocument(null); - - // setting the outcome will show the browse view again - return AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME + - AlfrescoNavigationHandler.OUTCOME_SEPARATOR + "browse"; - } - - @Override - protected String getErrorMessageId() - { - return "error_delete_file"; - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - // ------------------------------------------------------------------------------ - // Bean Getters and Setters - - /** - * Returns the confirmation to display to the user before deleting the content. - * - * @return The formatted message to display - */ - public String getConfirmMessage() - { - String fileConfirmMsg = null; - - Node document = this.browseBean.getDocument(); - - if(document.getType().equals(ContentModel.TYPE_MULTILINGUAL_CONTAINER)) - { - fileConfirmMsg = Application.getMessage(FacesContext.getCurrentInstance(), - "delete_ml_container_confirm"); - } - else if(document.hasAspect(ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION)) - { - fileConfirmMsg = Application.getMessage(FacesContext.getCurrentInstance(), - "delete_empty_translation_confirm"); - } - else if(document.hasAspect(ContentModel.ASPECT_MULTILINGUAL_DOCUMENT)) - { - fileConfirmMsg = Application.getMessage(FacesContext.getCurrentInstance(), - "delete_translation_confirm"); - } - else - { - String strHasMultipleParents = this.parameters.get("hasMultipleParents"); - if (strHasMultipleParents != null && "true".equals(strHasMultipleParents)) - { - fileConfirmMsg = Application.getMessage(FacesContext.getCurrentInstance(), - "delete_file_multiple_parents_confirm"); - } - else - { - fileConfirmMsg = Application.getMessage(FacesContext.getCurrentInstance(), - "delete_file_confirm"); - } - } - - return MessageFormat.format(fileConfirmMsg, - new Object[] {document.getName()}); - } - - /** - * @param multilingualContentService the Multilingual Content Service to set - */ - public void setMultilingualContentService(MultilingualContentService multilingualContentService) - { - this.multilingualContentService = multilingualContentService; - } - - protected MultilingualContentService getMultilingualContentService() - { - if (multilingualContentService == null) - { - multilingualContentService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getMultilingualContentService(); - } - return multilingualContentService; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/content/DocumentDetailsDialog.java b/war/src/main/java/org/alfresco/web/bean/content/DocumentDetailsDialog.java deleted file mode 100644 index 97ae1e357e..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/content/DocumentDetailsDialog.java +++ /dev/null @@ -1,1023 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.content; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Stack; - -import javax.faces.application.FacesMessage; -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.repo.transaction.RetryingTransactionHelper; -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.service.cmr.coci.CheckOutCheckInService; -import org.alfresco.service.cmr.lock.LockService; -import org.alfresco.service.cmr.ml.ContentFilterLanguagesService; -import org.alfresco.service.cmr.ml.EditionService; -import org.alfresco.service.cmr.ml.MultilingualContentService; -import org.alfresco.service.cmr.repository.ContentData; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.TemplateService; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.cmr.version.Version; -import org.alfresco.service.cmr.version.VersionHistory; -import org.alfresco.service.cmr.version.VersionService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.servlet.DownloadContentServlet; -import org.alfresco.web.bean.BaseDetailsBean; -import org.alfresco.web.bean.dialog.NavigationSupport; -import org.alfresco.web.bean.ml.SingleEditionBean; -import org.alfresco.web.bean.repository.MapNode; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.NodePropertyComparator; -import org.alfresco.web.ui.common.NodeListUtils; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.Utils.URLMode; -import org.alfresco.web.ui.common.component.UIActionLink; - -/** - * Backing bean providing access to the details of a document - * - * @author gavinc - */ -public class DocumentDetailsDialog extends BaseDetailsBean implements NavigationSupport -{ - private static final long serialVersionUID = -8579599071702546214L; - - private static final String OUTCOME_RETURN = null; - - private static final String MSG_HAS_FOLLOWING_CATEGORIES = "has_following_categories"; - private static final String MSG_NO_CATEGORIES_APPLIED = "no_categories_applied"; - private static final String MSG_SUCCESS_UNLOCK = "success_unlock"; - private static final String MSG_CURRENT = "current"; - private static final String MSG_ERROR_ASPECT_INLINEEDITABLE = "error_aspect_inlineeditable"; - private static final String MSG_ERROR_ASPECT_VERSIONING = "error_aspect_versioning"; - private static final String MSG_ERROR_ASPECT_CLASSIFY = "error_aspect_classify"; - private static final String MSG_DETAILS_OF = "details_of"; - private static final String MSG_LOCATION = "location"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - private final static String MSG_CLOSE = "close"; - - private static final String ML_VERSION_PANEL_ID = "ml-versions-panel"; - - private final static String DOC_DETAILS_STACK = "_alfDocDetailsStack"; - - transient protected LockService lockService; - transient protected VersionService versionService; - transient protected CheckOutCheckInService cociService; - transient protected MultilingualContentService multilingualContentService; - transient protected ContentFilterLanguagesService contentFilterLanguagesService; - transient protected EditionService editionService; - - private Node translationDocument; - - /** List of client light weight edition histories */ - private List editionHistory = null; - - /** For the client side iteration on the edition hitories list, it represents the index of the list */ - private int currentEditionCursorPosition; - - - // ------------------------------------------------------------------------------ - // Construction - - /** - * Default constructor - */ - public DocumentDetailsDialog() - { - // initial state of some panels that don't use the default - panels.put("version-history-panel", false); - panels.put("ml-info-panel", false); - panels.put("related-translation-panel", false); - } - - - // ------------------------------------------------------------------------------ - // Bean property getters and setters - - /** - * Resets any state that may be held by this bean - */ - public void reset() - { - // reset the workflow cache - this.workflowProperties = null; - } - - @Override - @SuppressWarnings("unchecked") - public void init(Map parameters) - { - super.init(parameters); - //Remember active node. - Stack stack = getRecentNodeRefsStack(); - stack.push(getNode().getNodeRef().getId()); - } - - @Override - @SuppressWarnings("unchecked") - public void restored() - { - super.restored(); - Stack stack = getRecentNodeRefsStack(); - if (stack.isEmpty() == false) - { - browseBean.setupContentAction((String) stack.peek(), true); - } - } - - @Override - @SuppressWarnings("unchecked") - public String cancel() - { - Stack stack = getRecentNodeRefsStack(); - if (stack.isEmpty() == false) - { - stack.pop(); - } - return super.cancel(); - } - - @SuppressWarnings("unchecked") - private Stack getRecentNodeRefsStack() - { - FacesContext fc = FacesContext.getCurrentInstance(); - Stack stack = (Stack) fc.getExternalContext().getSessionMap().get(DOC_DETAILS_STACK); - if (stack == null) - { - stack = new Stack(); - fc.getExternalContext().getSessionMap().put(DOC_DETAILS_STACK, stack); - } - return stack; - } - - /** - * Returns the URL to download content for the current document - * - * @return Content url to download the current document - */ - public String getUrl() - { - return (String)getDocument().getProperties().get("url"); - } - - /** - * @return the translation document for this node - */ - public Node getTranslationDocument() - { - return translationDocument; - } - - /** - * Before opening the ml container details, remeber the translation - * from which the action comes. - * - * @param node - */ - public void setTranslationDocument(Node node) - { - this.translationDocument = node; - } - - /** - * Returns the URL to the content for the current document - * - * @return Content url to the current document - */ - public String getBrowserUrl() - { - Node doc = getLinkResolvedNode(); - return Utils.generateURL(FacesContext.getCurrentInstance(), doc, URLMode.HTTP_INLINE); - } - - /** - * Returns the download URL to the content for the current document - * - * @return Download url to the current document - */ - public String getDownloadUrl() - { - Node doc = getLinkResolvedNode(); - return Utils.generateURL(FacesContext.getCurrentInstance(), doc, URLMode.HTTP_DOWNLOAD); - } - - /** - * Resolve the actual document Node from any Link object that may be proxying it - * - * @return current document Node or document Node resolved from any Link object - */ - protected Node getLinkResolvedNode() - { - Node document = getDocument(); - if (ApplicationModel.TYPE_FILELINK.equals(document.getType())) - { - NodeRef destRef = (NodeRef)document.getProperties().get(ContentModel.PROP_LINK_DESTINATION); - if (getNodeService().exists(destRef)) - { - document = new Node(destRef); - } - } - return document; - } - - /** - * Determines whether the current document is versionable - * - * @return true if the document has the versionable aspect - */ - public boolean isVersionable() - { - return getDocument().hasAspect(ContentModel.ASPECT_VERSIONABLE); - } - - /** - * @return true if the current document has the 'inlineeditable' aspect applied - */ - public boolean isInlineEditable() - { - return getDocument().hasAspect(ApplicationModel.ASPECT_INLINEEDITABLE); - } - - /** - * @return true if the current document has the 'inlineeditable' aspect applied - */ - public boolean isMultilingual() - { - return getDocument().hasAspect(ContentModel.ASPECT_MULTILINGUAL_DOCUMENT); - } - - /** - * Fixes an issue reported in https://issues.alfresco.com/jira/browse/ETWOONE-92 - * - * @return Returns action - */ - public String editContentProperties() - { - NodeRef nodeRef = getDocument().getNodeRef(); - if (this.getNodeService().exists(nodeRef)) - { - navigator.setupDispatchContext(getDocument()); - return "dialog:editContentProperties"; - } - else - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {nodeRef}) ); - return "browse"; - } - - } - - /** - * Save the state of the panel that was expanded/collapsed - */ - public void expandPanel(ActionEvent event) - { - super.expandPanel(event); - String id = event.getComponent().getId(); - - if(id.startsWith(ML_VERSION_PANEL_ID)) - { - this.currentEditionCursorPosition = Integer.parseInt(id.substring("ml-versions-panel".length())) - 1; - } - } - - /** - * Returns a list of objects representing the versions of the - * current document - * - * @return List of previous versions - */ - public List getVersionHistory() - { - List versions = new ArrayList(); - - if (getDocument().hasAspect(ContentModel.ASPECT_VERSIONABLE)) - { - VersionHistory history = this.getVersionService().getVersionHistory(getDocument().getNodeRef()); - - if (history != null) - { - for (Version version : history.getAllVersions()) - { - // create a map node representation of the version - MapNode clientVersion = new MapNode(version.getFrozenStateNodeRef()); - clientVersion.put("versionLabel", version.getVersionLabel()); - clientVersion.put("notes", version.getDescription()); - clientVersion.put("author", version.getCreator()); - clientVersion.put("versionDate", version.getCreatedDate()); - - if(getDocument().hasAspect(ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION)) - { - clientVersion.put("url", null); - } - else - { - clientVersion.put("url", DownloadContentServlet.generateBrowserURL(version.getFrozenStateNodeRef(), - clientVersion.getName())); - } - - - // add the client side version to the list - versions.add(clientVersion); - } - } - } - - return versions; - } - - /** - * For the client side iteration on the edition hitories list, - * return the next edition history. - * - * @return a light weight representation of an edition history - */ - public SingleEditionBean getNextSingleEditionBean() - { - currentEditionCursorPosition++; - - return getCurrentSingleEditionBean(); - } - - /** - * For the client side iteration on the edition hitories list, - * return the current edition history. - * - * @return a light weight representation of an edition history - */ - public SingleEditionBean getCurrentSingleEditionBean() - { - return editionHistory.get(currentEditionCursorPosition); - } - - /** - * Constructs a list of objects representing the editions of the - * logical document - * - * @return List of editions - */ - @SuppressWarnings("unused") - private List initEditionHistory() - { - // get the mlContainer - NodeRef mlContainer = getDocumentMlContainer().getNodeRef(); - - // get all editions (in descending order - ie. most recent first) - List orderedEditionList = new ArrayList(getEditionService().getEditions(mlContainer).getAllVersions()); - - // the list of Single Edition Bean to return - editionHistory = new ArrayList(orderedEditionList.size()); - - boolean firstEdition = true; - - // for each edition, init a SingleEditionBean - for (Version edition : orderedEditionList) - { - SingleEditionBean editionBean = new SingleEditionBean(); - - MapNode clientEdition = new MapNode(edition.getFrozenStateNodeRef()); - - String editionLabel = edition.getVersionLabel(); - if (firstEdition) - { - editionLabel += " (" + Application.getMessage(FacesContext.getCurrentInstance(), MSG_CURRENT) + ")"; - } - - clientEdition.put("editionLabel", editionLabel); - clientEdition.put("editionNotes", edition.getDescription()); - clientEdition.put("editionAuthor", edition.getCreator()); - clientEdition.put("editionDate", edition.getCreatedDate()); - - // Set the edition of the edition bean - editionBean.setEdition(clientEdition); - - // get translations - List translationHistories = null; - - if (firstEdition) - { - // Get the translations because the current edition doesn't content link with its - // translation in the version store. - Map translations = getMultilingualContentService().getTranslations(mlContainer); - translationHistories = new ArrayList(translations.size()); - for (NodeRef translation : translations.values()) - { - translationHistories.add(getVersionService().getVersionHistory(translation)); - } - } - else - { - translationHistories = getEditionService().getVersionedTranslations(edition); - } - - // add each translation in the SingleEditionBean - for (VersionHistory versionHistory : translationHistories) - { - // get the list of versions (in descending order - ie. most recent first) - List orderedVersions = new ArrayList(versionHistory.getAllVersions()); - - // the last version (ie. most recent) is the first version of the list - Version lastVersion = orderedVersions.get(0); - - // get the properties of the lastVersion - Map lastVersionProperties = getEditionService().getVersionedMetadatas(lastVersion); - Locale language = (Locale) lastVersionProperties.get(ContentModel.PROP_LOCALE); - - // create a map node representation of the last version - MapNode clientLastVersion = new MapNode(lastVersion.getFrozenStateNodeRef()); - - clientLastVersion.put("versionName", lastVersionProperties.get(ContentModel.PROP_NAME)); - // use the node service for the description to ensure that the returned value is a text and not a MLText - clientLastVersion.put("versionDescription", getNodeService().getProperty(lastVersion.getFrozenStateNodeRef(), ContentModel.PROP_DESCRIPTION)); - clientLastVersion.put("versionAuthor", lastVersionProperties.get(ContentModel.PROP_AUTHOR)); - clientLastVersion.put("versionCreatedDate", lastVersionProperties.get(ContentModel.PROP_CREATED)); - clientLastVersion.put("versionModifiedDate", lastVersionProperties.get(ContentModel.PROP_MODIFIED)); - clientLastVersion.put("versionLanguage", this.getContentFilterLanguagesService().convertToNewISOCode(language.getLanguage()).toUpperCase()); - - if(getNodeService().hasAspect(lastVersion.getFrozenStateNodeRef(), ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION)) - { - clientLastVersion.put("versionUrl", null); - } - else - { - clientLastVersion.put("versionUrl", DownloadContentServlet.generateBrowserURL(lastVersion.getFrozenStateNodeRef(), clientLastVersion.getName())); - } - - // add a translation of the editionBean - editionBean.addTranslations(clientLastVersion); - } - editionHistory.add(editionBean); - firstEdition = false; - } - - return editionHistory; - } - - - /** - * Determines whether the current document has any categories applied - * - * @return true if the document has categories attached - */ - public boolean isCategorised() - { - return getDocument().hasAspect(ContentModel.ASPECT_GEN_CLASSIFIABLE); - } - - /** - * Returns a list of objects representing the categories applied to the - * current document - * - * @return List of categories - */ - public String getCategoriesOverviewHTML() - { - String html = null; - - if (isCategorised()) - { - // we know for now that the general classifiable aspect only will be - // applied so we can retrive the categories property direclty - Collection categories = (Collection)this.getNodeService().getProperty( - getDocument().getNodeRef(), ContentModel.PROP_CATEGORIES); - - if (categories == null || categories.size() == 0) - { - html = Application.getMessage(FacesContext.getCurrentInstance(), MSG_NO_CATEGORIES_APPLIED); - } - else - { - StringBuilder builder = new StringBuilder(Application.getMessage(FacesContext.getCurrentInstance(), - MSG_HAS_FOLLOWING_CATEGORIES)); - - builder.append("
    "); - for (NodeRef ref : categories) - { - if (this.getNodeService().exists(ref)) - { - builder.append("
  • "); - builder.append(Utils.encode(Repository.getNameForCategoryNode(this.getNodeService(), ref))); - builder.append("
  • "); - } - } - builder.append("
"); - - html = builder.toString(); - } - } - - return html; - } - - /** - * Applies the classifiable aspect to the current document - */ - public void applyClassifiable() - { - try - { - RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(FacesContext.getCurrentInstance()); - RetryingTransactionCallback callback = new RetryingTransactionCallback() - { - public Object execute() throws Throwable - { - // add the general classifiable aspect to the node - getNodeService().addAspect(getDocument().getNodeRef(), ContentModel.ASPECT_GEN_CLASSIFIABLE, null); - return null; - } - }; - txnHelper.doInTransaction(callback); - - // reset the state of the current document - getDocument().reset(); - } - catch (Throwable e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), MSG_ERROR_ASPECT_CLASSIFY), e.getMessage()), e); - ReportedException.throwIfNecessary(e); - } - } - - /** - * Applies the versionable aspect to the current document - */ - public void applyVersionable() - { - try - { - FacesContext context = FacesContext.getCurrentInstance(); - RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(context); - RetryingTransactionCallback callback = new RetryingTransactionCallback() - { - public Object execute() throws Throwable - { - // add the versionable aspect to the node - getNodeService().addAspect(getDocument().getNodeRef(), ContentModel.ASPECT_VERSIONABLE, null); - return null; - } - }; - txnHelper.doInTransaction(callback); - - // reset the state of the current document - getDocument().reset(); - - // get hold of the main property sheet on the page and remove the children to force a refresh - UIComponent comp = context.getViewRoot().findComponent("dialog:dialog-body:document-props"); - if (comp != null) - { - comp.getChildren().clear(); - } - } - catch (Throwable e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), MSG_ERROR_ASPECT_VERSIONING), e.getMessage()), e); - ReportedException.throwIfNecessary(e); - } - } - - /** - * Action Handler to unlock a locked document - */ - public void unlock(final ActionEvent event) - { - final FacesContext fc = FacesContext.getCurrentInstance(); - - try - { - RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(FacesContext.getCurrentInstance()); - RetryingTransactionCallback callback = new RetryingTransactionCallback() - { - public Object execute() throws Throwable - { - getLockService().unlock(getNode().getNodeRef()); - - String msg = Application.getMessage(fc, MSG_SUCCESS_UNLOCK); - FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg); - String formId = Utils.getParentForm(fc, event.getComponent()).getClientId(fc); - fc.addMessage(formId + ':' + getPropertiesPanelId(), facesMsg); - - getNode().reset(); - return null; - } - }; - txnHelper.doInTransaction(callback); - } - catch (Throwable e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - fc, Repository.ERROR_GENERIC), e.getMessage()), e); - ReportedException.throwIfNecessary(e); - } - } - - /** - * Applies the inlineeditable aspect to the current document - */ - public String applyInlineEditable() - { - try - { - RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(FacesContext.getCurrentInstance()); - RetryingTransactionCallback callback = new RetryingTransactionCallback() - { - public Object execute() throws Throwable - { - // add the inlineeditable aspect to the node - Map props = new HashMap(1, 1.0f); - String contentType = null; - ContentData contentData = (ContentData)getDocument().getProperties().get(ContentModel.PROP_CONTENT); - if (contentData != null) - { - contentType = contentData.getMimetype(); - } - if (contentType != null) - { - // set the property to true by default if the filetype is a known content type - if (MimetypeMap.MIMETYPE_HTML.equals(contentType) || - MimetypeMap.MIMETYPE_TEXT_PLAIN.equals(contentType) || - MimetypeMap.MIMETYPE_XML.equals(contentType) || - MimetypeMap.MIMETYPE_TEXT_CSS.equals(contentType) || - MimetypeMap.MIMETYPE_JAVASCRIPT.equals(contentType)) - { - props.put(ApplicationModel.PROP_EDITINLINE, true); - } - } - getNodeService().addAspect(getDocument().getNodeRef(), ApplicationModel.ASPECT_INLINEEDITABLE, props); - - return null; - } - }; - txnHelper.doInTransaction(callback); - - // reset the state of the current document - getDocument().reset(); - } - catch (Throwable e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), MSG_ERROR_ASPECT_INLINEEDITABLE), e.getMessage()), e); - ReportedException.throwIfNecessary(e); - } - - // force recreation of the details view - this means the properties sheet component will reinit - return OUTCOME_RETURN; - } - - /** - * Navigates to next item in the list of content for the current Space - */ - public void nextItem(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - List nodes = this.browseBean.getContent(); - if (nodes.size() > 1) - { - String currentSortColumn = this.browseBean.getContentRichList().getCurrentSortColumn(); - if (currentSortColumn != null) - { - boolean currentSortDescending = this.browseBean.getContentRichList().isCurrentSortDescending(); - Collections.sort(nodes, new NodePropertyComparator(currentSortColumn, !currentSortDescending)); - } - Node next = NodeListUtils.nextItem(nodes, id); - getRecentNodeRefsStack().clear(); - this.browseBean.setupContentAction(next.getId(), false); - } - } - } - - /** - * Navigates to the previous item in the list of content for the current Space - */ - public void previousItem(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - List nodes = this.browseBean.getContent(); - if (nodes.size() > 1) - { - String currentSortColumn = this.browseBean.getContentRichList().getCurrentSortColumn(); - if (currentSortColumn != null) - { - boolean currentSortDescending = this.browseBean.getContentRichList().isCurrentSortDescending(); - Collections.sort(nodes, new NodePropertyComparator(currentSortColumn, !currentSortDescending)); - } - Node previous = NodeListUtils.previousItem(nodes, id); - getRecentNodeRefsStack().clear(); - this.browseBean.setupContentAction(previous.getId(), false); - } - } - } - - /** - * @see org.alfresco.web.bean.BaseDetailsBean#getPropertiesPanelId() - */ - protected String getPropertiesPanelId() - { - return "document-props"; - } - - /** - * Returns a model for use by a template on the Document Details page. - * - * @return model containing current document and current space info. - */ - public Map getTemplateModel() - { - Map model = new HashMap(2, 1.0f); - - model.put("document", getDocument().getNodeRef()); - model.put("space", this.navigator.getCurrentNode().getNodeRef()); - model.put(TemplateService.KEY_IMAGE_RESOLVER, imageResolver); - - return model; - } - - /** - * Returns whether the current document is locked - * - * @return true if the document is checked out - */ - public boolean isLocked() - { - return getDocument().isLocked(); - } - - /** - * Returns whether the current document is a working copy - * - * @return true if the document is a working copy - */ - public boolean isWorkingCopy() - { - return getDocument().hasAspect(ContentModel.ASPECT_WORKING_COPY); - } - - /** - * @return the working copy document Node for this document if found and the - * current has permission or null if not - */ - public Node getWorkingCopyDocument() - { - Node workingCopyNode = null; - - if (isLocked()) - { - NodeRef workingCopyRef = this.getCheckOutCheckInService().getWorkingCopy(getDocument().getNodeRef()); - if (workingCopyRef != null) - { - workingCopyNode = new Node(workingCopyRef); - - // if the current user does not have read permission on - // working copy return null - if (workingCopyNode.hasPermission(PermissionService.READ) == false) - { - workingCopyNode = null; - } - } - } - - return workingCopyNode; - } - - /** - * Returns whether the current document is a working copy owned by the current User - * - * @return true if the document is a working copy owner by the current User - */ - public boolean isOwner() - { - return getDocument().isWorkingCopyOwner(); - } - - /** - * Returns the Node this bean is currently representing - * - * @return The Node - */ - public Node getNode() - { - return this.browseBean.getDocument(); - } - - /** - * Returns the document this bean is currently representing - * - * @return The document Node - */ - public Node getDocument() - { - return this.getNode(); - } - - /** - * Returns the ml container of the document this bean is currently representing - * - * @return The document multilingual container NodeRef - */ - public Node getDocumentMlContainer() - { - Node currentNode = getNode(); - - if(ContentModel.TYPE_MULTILINGUAL_CONTAINER.equals(currentNode.getType())) - { - return currentNode; - } - else - { - NodeRef nodeRef = getNode().getNodeRef(); - - return new Node(getMultilingualContentService().getTranslationContainer(nodeRef)); - } - } - /** - * Sets the lock service instance the bean should use - * - * @param lockService The LockService - */ - public void setLockService(LockService lockService) - { - this.lockService = lockService; - } - - protected LockService getLockService() - { - if (lockService == null) - { - lockService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getLockService(); - } - return lockService; - } - - /** - * Sets the version service instance the bean should use - * - * @param versionService The VersionService - */ - public void setVersionService(VersionService versionService) - { - this.versionService = versionService; - } - - protected VersionService getVersionService() - { - if (versionService == null) - { - versionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getVersionService(); - } - return versionService; - } - - /** - * Sets the checkincheckout service instance the bean should use - * - * @param cociService The CheckOutCheckInService - */ - public void setCheckOutCheckInService(CheckOutCheckInService cociService) - { - this.cociService = cociService; - } - - protected CheckOutCheckInService getCheckOutCheckInService() - { - if (cociService == null) - { - cociService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getCheckOutCheckInService(); - } - return cociService; - } - - /** - * @param multilingualContentService the multilingual ContentService to set - */ - public void setMultilingualContentService(MultilingualContentService multilingualContentService) - { - this.multilingualContentService = multilingualContentService; - } - - protected MultilingualContentService getMultilingualContentService() - { - if (multilingualContentService == null) - { - multilingualContentService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getMultilingualContentService(); - } - return multilingualContentService; - } - - /** - * @param contentFilterLanguagesService The Content Filter Languages Service to set. - */ - public void setContentFilterLanguagesService(ContentFilterLanguagesService contentFilterLanguagesService) - { - this.contentFilterLanguagesService = contentFilterLanguagesService; - } - - protected ContentFilterLanguagesService getContentFilterLanguagesService() - { - if (contentFilterLanguagesService == null) - { - contentFilterLanguagesService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getContentFilterLanguagesService(); - } - return contentFilterLanguagesService; - } - - /** - * @param editionService The Edition Service to set. - */ - public void setEditionService(EditionService editionService) - { - this.editionService = editionService; - } - - protected EditionService getEditionService() - { - if (editionService == null) - { - editionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getEditionService(); - } - return editionService; - } - - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } - - public String getContainerSubTitle() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_LOCATION) + ": " + - getDocument().getNodePath().toDisplayPath(getNodeService(), getPermissionService()); - } - - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_DETAILS_OF) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) + getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - public String getCurrentItemId() - { - return getId(); - } - - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - public String getOutcome() - { - return "dialog:close:dialog:showDocDetails"; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/content/DocumentLinkDetailsDialog.java b/war/src/main/java/org/alfresco/web/bean/content/DocumentLinkDetailsDialog.java deleted file mode 100644 index 93f9c7a943..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/content/DocumentLinkDetailsDialog.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.content; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.TemplateService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.BaseDetailsBean; -import org.alfresco.web.bean.dialog.NavigationSupport; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.ui.common.NodeListUtils; -import org.alfresco.web.ui.common.NodePropertyComparator; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.Utils.URLMode; -import org.alfresco.web.ui.common.component.UIActionLink; - -public class DocumentLinkDetailsDialog extends BaseDetailsBean implements NavigationSupport -{ - private static final long serialVersionUID = 4716260640608281667L; - - private static final String MSG_DETAILS_OF = "details_of"; - private static final String MSG_LOCATION = "location"; - private final static String MSG_CLOSE = "close"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - /** - * Returns the document this bean is currently representing - * - * @return The document Node - */ - public Node getDocument() - { - return this.getNode(); - } - - @Override - protected Node getLinkResolvedNode() - { - Node document = getDocument(); - if (ApplicationModel.TYPE_FILELINK.equals(document.getType())) - { - NodeRef destRef = (NodeRef)document.getProperties().get(ContentModel.PROP_LINK_DESTINATION); - if (getNodeService().exists(destRef)) - { - document = new Node(destRef); - } - } - return document; - } - - @Override - public Node getNode() - { - return this.browseBean.getDocument(); - } - - @Override - protected String getPropertiesPanelId() - { - return "document-props"; - } - - @Override - public Map getTemplateModel() - { - Map model = new HashMap(2, 1.0f); - - model.put("document", getDocument().getNodeRef()); - model.put("space", this.navigator.getCurrentNode().getNodeRef()); - model.put(TemplateService.KEY_IMAGE_RESOLVER, imageResolver); - - return model; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - public String getCurrentItemId() - { - return getId(); - } - - public String getOutcome() - { - return "dialog:close:dialog:showDocDetails"; - } - - public void nextItem(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - List nodes = this.browseBean.getContent(); - if (nodes.size() > 1) - { - String currentSortColumn = this.browseBean.getContentRichList().getCurrentSortColumn(); - boolean currentSortDescending = this.browseBean.getContentRichList().isCurrentSortDescending(); - Collections.sort(nodes, new NodePropertyComparator(currentSortColumn, !currentSortDescending)); - Node next = NodeListUtils.nextItem(nodes, id); - this.browseBean.setupContentAction(next.getId(), false); - } - } - - } - - public void previousItem(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - List nodes = this.browseBean.getContent(); - if (nodes.size() > 1) - { - String currentSortColumn = this.browseBean.getContentRichList().getCurrentSortColumn(); - boolean currentSortDescending = this.browseBean.getContentRichList().isCurrentSortDescending(); - Collections.sort(nodes, new NodePropertyComparator(currentSortColumn, !currentSortDescending)); - Node previous = NodeListUtils.previousItem(nodes, id); - this.browseBean.setupContentAction(previous.getId(), false); - } - } - - } - - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } - - public String getContainerSubTitle() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_LOCATION) + ": " + - getDocument().getNodePath().toDisplayPath(getNodeService(), getPermissionService()); - } - - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_DETAILS_OF) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) + getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - /** - * Returns the URL to the content for the current document - * - * @return Content url to the current document - */ - public String getBrowserUrl() - { - Node doc = getLinkResolvedNode(); - return Utils.generateURL(FacesContext.getCurrentInstance(), doc, URLMode.HTTP_INLINE); - } - - /** - * Returns the download URL to the content for the current document - * - * @return Download url to the current document - */ - public String getDownloadUrl() - { - Node doc = getLinkResolvedNode(); - return Utils.generateURL(FacesContext.getCurrentInstance(), doc, URLMode.HTTP_DOWNLOAD); - } - - /** - * Returns whether the current document is locked - * - * @return true if the document is checked out - */ - public boolean isLocked() - { - return getDocument().isLocked(); - } - - /** - * Returns the URL to download content for the current document - * - * @return Content url to download the current document - */ - public String getUrl() - { - return (String)getDocument().getProperties().get("url"); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/content/DocumentPropertiesDialog.java b/war/src/main/java/org/alfresco/web/bean/content/DocumentPropertiesDialog.java deleted file mode 100644 index 77d84b4759..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/content/DocumentPropertiesDialog.java +++ /dev/null @@ -1,452 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.content; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.faces.model.SelectItem; -import javax.transaction.UserTransaction; - -import org.springframework.extensions.config.Config; -import org.springframework.extensions.config.ConfigService; -import org.alfresco.model.ContentModel; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.dictionary.DataTypeDefinition; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.cmr.model.FileExistsException; -import org.alfresco.service.cmr.model.FileFolderService; -import org.alfresco.service.cmr.repository.AssociationRef; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.ContentData; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.MimetypeService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.BrowseBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.config.PropertySheetConfigElement; -import org.alfresco.web.data.IDataContainer; -import org.alfresco.web.data.QuickSort; -import org.alfresco.web.ui.common.Utils; - -/** - * Backing bean for the edit document properties dialog - * - * @author gavinc - */ -public class DocumentPropertiesDialog implements Serializable -{ - private static final long serialVersionUID = 3065164840163513872L; - - private static final String TEMP_PROP_MIMETYPE = "mimetype"; - private static final String TEMP_PROP_ENCODING = "encoding"; - - transient private NodeService nodeService; - transient private FileFolderService fileFolderService; - transient private DictionaryService dictionaryService; - - protected BrowseBean browseBean; - private List contentTypes; - private Node editableNode; - private Boolean hasOtherProperties; - - /** - * Returns the node being edited - * - * @return The node being edited - */ - public Node getEditableNode() - { - return this.editableNode; - } - - /** - * Event handler called to setup the document for property editing - * - * @param event The event - */ - public void setupDocumentForAction(ActionEvent event) - { - this.editableNode = new Node(this.browseBean.getDocument().getNodeRef()); - - // special case for Mimetype - since this is a sub-property of the ContentData object - // we must extract it so it can be edited in the client, then we check for it later - // and create a new ContentData object to wrap it and it's associated URL - ContentData content = (ContentData)this.editableNode.getProperties().get(ContentModel.PROP_CONTENT); - if (content != null) - { - this.editableNode.getProperties().put(TEMP_PROP_MIMETYPE, content.getMimetype()); - this.editableNode.getProperties().put(TEMP_PROP_ENCODING, content.getEncoding()); - } - - this.hasOtherProperties = null; - } - - /** - * Event handler used to save the edited properties back to the repository - * - * @return The outcome - */ - public String save() - { - String outcome = "cancel"; - - UserTransaction tx = null; - - try - { - tx = Repository.getUserTransaction(FacesContext.getCurrentInstance()); - tx.begin(); - - NodeRef nodeRef = this.browseBean.getDocument().getNodeRef(); - Map props = this.editableNode.getProperties(); - - // get the name and move the node as necessary - String name = (String) props.get(ContentModel.PROP_NAME); - if (name != null) - { - getFileFolderService().rename(nodeRef, name); - } - - Map properties = getNodeService().getProperties(nodeRef); - // we need to put all the properties from the editable bag back into - // the format expected by the repository - - // Deal with the special mimetype property for ContentData - String mimetype = (String)props.get(TEMP_PROP_MIMETYPE); - if (mimetype != null) - { - // remove temporary prop from list so it isn't saved with the others - props.remove(TEMP_PROP_MIMETYPE); - ContentData contentData = (ContentData)props.get(ContentModel.PROP_CONTENT); - if (contentData != null) - { - contentData = ContentData.setMimetype(contentData, mimetype); - props.put(ContentModel.PROP_CONTENT.toString(), contentData); - } - } - - // Deal with the special encoding property for ContentData - String encoding = (String) props.get(TEMP_PROP_ENCODING); - if (encoding != null) - { - // remove temporary prop from list so it isn't saved with the others - props.remove(TEMP_PROP_ENCODING); - ContentData contentData = (ContentData)props.get(ContentModel.PROP_CONTENT); - if (contentData != null) - { - contentData = ContentData.setEncoding(contentData, encoding); - props.put(ContentModel.PROP_CONTENT.toString(), contentData); - } - } - - // extra and deal with the Author prop if the aspect has not been applied yet - String author = (String)props.get(ContentModel.PROP_AUTHOR); - if (author != null && author.length() != 0) - { - // add aspect if required - if (getNodeService().hasAspect(nodeRef, ContentModel.ASPECT_AUTHOR) == false) - { - Map authorProps = new HashMap(1, 1.0f); - authorProps.put(ContentModel.PROP_AUTHOR, author); - getNodeService().addAspect(nodeRef, ContentModel.ASPECT_AUTHOR, authorProps); - } - // else it will get updated in the later setProperties() call - } - - // deal with adding the "titled" aspect if required - String title = (String)props.get(ContentModel.PROP_TITLE); - String description = (String)props.get(ContentModel.PROP_DESCRIPTION); - if (title != null || description != null) - { - // add the aspect to be sure it's present - getNodeService().addAspect(nodeRef, ContentModel.ASPECT_TITLED, null); - // props will get added later in setProperties() - } - - // add the remaining properties - Iterator iterProps = props.keySet().iterator(); - while (iterProps.hasNext()) - { - String propName = iterProps.next(); - QName qname = QName.createQName(propName); - - // make sure the property is represented correctly - Serializable propValue = (Serializable)props.get(propName); - - // check for empty strings when using number types, set to null in this case - if ((propValue != null) && (propValue instanceof String) && - (propValue.toString().length() == 0)) - { - PropertyDefinition propDef = getDictionaryService().getProperty(qname); - if (propDef != null) - { - if (propDef.getDataType().getName().equals(DataTypeDefinition.DOUBLE) || - propDef.getDataType().getName().equals(DataTypeDefinition.FLOAT) || - propDef.getDataType().getName().equals(DataTypeDefinition.INT) || - propDef.getDataType().getName().equals(DataTypeDefinition.LONG)) - { - propValue = null; - } - } - } - - properties.put(qname, propValue); - } - - // send the properties back to the repository - getNodeService().setProperties(this.browseBean.getDocument().getNodeRef(), properties); - - // we also need to persist any association changes that may have been made - - // add any associations added in the UI - Map> addedAssocs = this.editableNode.getAddedAssociations(); - for (Map typedAssoc : addedAssocs.values()) - { - for (AssociationRef assoc : typedAssoc.values()) - { - getNodeService().createAssociation(assoc.getSourceRef(), assoc.getTargetRef(), assoc.getTypeQName()); - } - } - - // remove any association removed in the UI - Map> removedAssocs = this.editableNode.getRemovedAssociations(); - for (Map typedAssoc : removedAssocs.values()) - { - for (AssociationRef assoc : typedAssoc.values()) - { - getNodeService().removeAssociation(assoc.getSourceRef(), assoc.getTargetRef(), assoc.getTypeQName()); - } - } - - // add any child associations added in the UI - Map> addedChildAssocs = this.editableNode.getAddedChildAssociations(); - for (Map typedAssoc : addedChildAssocs.values()) - { - for (ChildAssociationRef assoc : typedAssoc.values()) - { - getNodeService().addChild(assoc.getParentRef(), assoc.getChildRef(), assoc.getTypeQName(), assoc.getTypeQName()); - } - } - - // remove any child association removed in the UI - Map> removedChildAssocs = this.editableNode.getRemovedChildAssociations(); - for (Map typedAssoc : removedChildAssocs.values()) - { - for (ChildAssociationRef assoc : typedAssoc.values()) - { - getNodeService().removeChild(assoc.getParentRef(), assoc.getChildRef()); - } - } - - // commit the transaction - tx.commit(); - - // set the outcome to refresh - outcome = "finish"; - - // reset the document held by the browse bean as it's just been updated - this.browseBean.getDocument().reset(); - } - catch (FileExistsException e) - { - // rollback the transaction - try { if (tx != null) {tx.rollback();} } catch (Exception ex) {} - // print status message - String statusMsg = MessageFormat.format( - Application.getMessage( - FacesContext.getCurrentInstance(), "error_exists"), - e.getName()); - Utils.addErrorMessage(statusMsg); - // no outcome - outcome = null; - } - catch (InvalidNodeRefException err) - { - // rollback the transaction - try { if (tx != null) {tx.rollback();} } catch (Exception ex) {} - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {this.browseBean.getDocument().getId()}) ); - // this failure means the node no longer exists - we cannot show the doc properties screen - outcome = "browse"; - } - catch (Throwable e) - { - // rollback the transaction - try { if (tx != null) {tx.rollback();} } catch (Exception ex) {} - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), e.getMessage()), e); - } - - return outcome; - } - - public Map getProperties() - { - return this.editableNode.getProperties(); - } - - /** - * @return Returns a list of content types to allow the user to select from - */ - public List getContentTypes() - { - if (this.contentTypes == null) - { - this.contentTypes = new ArrayList(80); - ServiceRegistry registry = Repository.getServiceRegistry(FacesContext.getCurrentInstance()); - MimetypeService mimetypeService = registry.getMimetypeService(); - - // get the mime type display names - Map mimeTypes = mimetypeService.getDisplaysByMimetype(); - for (String mimeType : mimeTypes.keySet()) - { - this.contentTypes.add(new SelectItem(mimeType, mimeTypes.get(mimeType))); - } - - // make sure the list is sorted by the values - QuickSort sorter = new QuickSort(this.contentTypes, "label", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - } - - return this.contentTypes; - } - - /** - * Determines whether this document has any other properties other than the - * default set to display to the user. - * - * @return true of there are properties to show, false otherwise - */ - public boolean getOtherPropertiesPresent() - { - if ((this.hasOtherProperties == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - // we need to use the config service to see whether there are any - // editable properties configured for this document. - ConfigService configSvc = Application.getConfigService(FacesContext.getCurrentInstance()); - Config configProps = configSvc.getConfig(this.editableNode); - PropertySheetConfigElement propsToDisplay = (PropertySheetConfigElement)configProps. - getConfigElement("property-sheet"); - - if (propsToDisplay != null && propsToDisplay.getEditableItemNamesToShow().size() > 0) - { - this.hasOtherProperties = Boolean.TRUE; - } - else - { - this.hasOtherProperties = Boolean.FALSE; - } - } - - return this.hasOtherProperties.booleanValue(); - } - - /** - * @return Returns the nodeService. - */ - public NodeService getNodeService() - { - if (nodeService == null) - { - nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - } - - return this.nodeService; - } - - /** - * @param nodeService The nodeService to set. - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - /** - * @param fileFolderService the file and folder model-specific functions - */ - public void setFileFolderService(FileFolderService fileFolderService) - { - this.fileFolderService = fileFolderService; - } - - protected FileFolderService getFileFolderService() - { - if (fileFolderService == null) - { - fileFolderService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getFileFolderService(); - } - return fileFolderService; - } - - /** - * Sets the DictionaryService to use when persisting metadata - * - * @param dictionaryService The DictionaryService - */ - public void setDictionaryService(DictionaryService dictionaryService) - { - this.dictionaryService = dictionaryService; - } - - protected DictionaryService getDictionaryService() - { - if (dictionaryService == null) - { - dictionaryService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getDictionaryService(); - } - return dictionaryService; - } - - /** - * @return The BrowseBean - */ - public BrowseBean getBrowseBean() - { - return this.browseBean; - } - - /** - * @param browseBean The BrowseBean to set. - */ - public void setBrowseBean(BrowseBean browseBean) - { - this.browseBean = browseBean; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/content/EditContentPropertiesDialog.java b/war/src/main/java/org/alfresco/web/bean/content/EditContentPropertiesDialog.java deleted file mode 100644 index 803bf4698a..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/content/EditContentPropertiesDialog.java +++ /dev/null @@ -1,331 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.content; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Iterator; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.springframework.extensions.surf.util.I18NUtil; -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.dictionary.DataTypeDefinition; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.cmr.model.FileExistsException; -import org.alfresco.service.cmr.repository.AssociationRef; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.ContentData; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.Utils; - -/** - * Bean implementation of the "Edit Content Properties" dialog. - * - * @author gavinc - */ -public class EditContentPropertiesDialog extends BaseDialogBean -{ - private static final long serialVersionUID = -5681296528149487178L; - - protected static final String TEMP_PROP_MIMETYPE = "mimetype"; - protected static final String TEMP_PROP_ENCODING = "encoding"; - - protected Node editableNode; - - // ------------------------------------------------------------------------------ - // Dialog implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - // setup the editable node - this.editableNode = initEditableNode(); - - if(editableNode != null) - { - - // special case for Mimetype - since this is a sub-property of the ContentData object - // we must extract it so it can be edited in the client, then we check for it later - // and create a new ContentData object to wrap it and it's associated URL - ContentData content = (ContentData)this.editableNode.getProperties().get(ContentModel.PROP_CONTENT); - if (content != null) - { - this.editableNode.getProperties().put(TEMP_PROP_MIMETYPE, content.getMimetype()); - this.editableNode.getProperties().put(TEMP_PROP_ENCODING, content.getEncoding()); - } - } - } - - /** - * Init the editable Node - */ - protected Node initEditableNode() - { - final Node document = this.browseBean.getDocument(); - if (document != null) - { - return new Node(document.getNodeRef()); - } - return null; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) - throws Exception - { - NodeRef nodeRef = this.editableNode.getNodeRef(); - Map editedProps = this.editableNode.getProperties(); - - // get the name and move the node as necessary - String name = (String) editedProps.get(ContentModel.PROP_NAME); - if (name != null) - { - getFileFolderService().rename(nodeRef, name); - } - - // we need to put all the properties from the editable bag back into - // the format expected by the repository - Map repoProps = this.getNodeService().getProperties(nodeRef); - - // Extract and deal with the special mimetype property for ContentData - String mimetype = (String) editedProps.get(TEMP_PROP_MIMETYPE); - if (mimetype != null) - { - // remove temporary prop from list so it isn't saved with the others - editedProps.remove(TEMP_PROP_MIMETYPE); - ContentData contentData = (ContentData)editedProps.get(ContentModel.PROP_CONTENT); - if (contentData != null) - { - contentData = ContentData.setMimetype(contentData, mimetype); - editedProps.put(ContentModel.PROP_CONTENT.toString(), contentData); - } - } - // Extract and deal with the special encoding property for ContentData - String encoding = (String) editedProps.get(TEMP_PROP_ENCODING); - if (encoding != null) - { - // remove temporary prop from list so it isn't saved with the others - editedProps.remove(TEMP_PROP_ENCODING); - ContentData contentData = (ContentData) editedProps.get(ContentModel.PROP_CONTENT); - if (contentData != null) - { - contentData = ContentData.setEncoding(contentData, encoding); - editedProps.put(ContentModel.PROP_CONTENT.toString(), contentData); - } - } - - // add the "author" aspect if required, properties will get set below - if (this.getNodeService().hasAspect(nodeRef, ContentModel.ASPECT_AUTHOR) == false) - { - this.getNodeService().addAspect(nodeRef, ContentModel.ASPECT_AUTHOR, null); - } - - // add the "titled" aspect if required, properties will get set below - if (this.getNodeService().hasAspect(nodeRef, ContentModel.ASPECT_TITLED) == false) - { - getNodeService().addAspect(nodeRef, ContentModel.ASPECT_TITLED, null); - } - - // add the remaining properties - Iterator iterProps = editedProps.keySet().iterator(); - while (iterProps.hasNext()) - { - String propName = iterProps.next(); - QName qname = QName.createQName(propName); - - // make sure the property is represented correctly - Serializable propValue = (Serializable)editedProps.get(propName); - - // check for empty strings when using number types, set to null in this case - if (propValue instanceof String) - { - PropertyDefinition propDef = this.getDictionaryService().getProperty(qname); - if (((String)propValue).length() == 0) - { - if (propDef != null) - { - if (propDef.getDataType().getName().equals(DataTypeDefinition.DOUBLE) || - propDef.getDataType().getName().equals(DataTypeDefinition.FLOAT) || - propDef.getDataType().getName().equals(DataTypeDefinition.INT) || - propDef.getDataType().getName().equals(DataTypeDefinition.LONG)) - { - propValue = null; - } - } - } - // handle locale strings to Locale objects - else if (propDef != null && propDef.getDataType().getName().equals(DataTypeDefinition.LOCALE)) - { - propValue = I18NUtil.parseLocale((String)propValue); - } - } - - repoProps.put(qname, propValue); - } - - // send the properties back to the repository - this.getNodeService().setProperties(nodeRef, repoProps); - - // we also need to persist any association changes that may have been made - - // add any associations added in the UI - Map> addedAssocs = this.editableNode.getAddedAssociations(); - for (Map typedAssoc : addedAssocs.values()) - { - for (AssociationRef assoc : typedAssoc.values()) - { - this.getNodeService().createAssociation(assoc.getSourceRef(), assoc.getTargetRef(), assoc.getTypeQName()); - } - } - - // remove any association removed in the UI - Map> removedAssocs = this.editableNode.getRemovedAssociations(); - for (Map typedAssoc : removedAssocs.values()) - { - for (AssociationRef assoc : typedAssoc.values()) - { - this.getNodeService().removeAssociation(assoc.getSourceRef(), assoc.getTargetRef(), assoc.getTypeQName()); - } - } - - // add any child associations added in the UI - Map> addedChildAssocs = this.editableNode.getAddedChildAssociations(); - for (Map typedAssoc : addedChildAssocs.values()) - { - for (ChildAssociationRef assoc : typedAssoc.values()) - { - this.getNodeService().addChild(assoc.getParentRef(), assoc.getChildRef(), assoc.getTypeQName(), assoc.getTypeQName()); - } - } - - // remove any child association removed in the UI - Map> removedChildAssocs = this.editableNode.getRemovedChildAssociations(); - for (Map typedAssoc : removedChildAssocs.values()) - { - for (ChildAssociationRef assoc : typedAssoc.values()) - { - this.getNodeService().removeChild(assoc.getParentRef(), assoc.getChildRef()); - } - } - - return outcome; - } - - @Override - protected String doPostCommitProcessing(FacesContext context, String outcome) - { - // reset the document held by the browse bean as it's just been updated - this.browseBean.getDocument().reset(); - - return outcome; - } - - /** - * Formats the error message to display if an error occurs during finish processing - * - * @param exception The exception - * @return The formatted message - */ - @Override - protected String formatErrorMessage(Throwable exception) - { - if(editableNode != null) - { - - // special case for Mimetype - since this is a sub-property of the ContentData object - // we must extract it so it can be edited in the client, then we check for it later - // and create a new ContentData object to wrap it and it's associated URL - ContentData content = (ContentData)this.editableNode.getProperties().get(ContentModel.PROP_CONTENT); - if (content != null) - { - this.editableNode.getProperties().put(TEMP_PROP_MIMETYPE, content.getMimetype()); - this.editableNode.getProperties().put(TEMP_PROP_ENCODING, content.getEncoding()); - } - } - - if (exception instanceof FileExistsException) - { - return MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_EXISTS), - ((FileExistsException)exception).getName()); - } - else if (exception instanceof InvalidNodeRefException) - { - return MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), - new Object[] {this.browseBean.getDocument().getId()}); - } - else - { - return super.formatErrorMessage(exception); - } - } - - @Override - protected String getErrorOutcome(Throwable exception) - { - if (exception instanceof InvalidNodeRefException) - { - // this failure means the node no longer exists - we cannot show - // the content properties screen again so go back to the main page - return "browse"; - } - else - { - return super.getErrorOutcome(exception); - } - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - - // ------------------------------------------------------------------------------ - // Bean getters and setters - - /** - * Returns the node being edited - * - * @return The node being edited - */ - public Node getEditableNode() - { - return this.editableNode; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/content/EditContentWizard.java b/war/src/main/java/org/alfresco/web/bean/content/EditContentWizard.java deleted file mode 100644 index 254e0b7ca4..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/content/EditContentWizard.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.content; - -import java.io.File; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.service.cmr.repository.ContentWriter; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.bean.repository.Node; - -/** - * Bean implementation for the "Edit Content Wizard" dialog - */ -public class EditContentWizard extends CreateContentWizard -{ - private static final long serialVersionUID = 1640754719164511019L; - - private NodeRef nodeRef; - - // ------------------------------------------------------------------------------ - // Wizard implementation - - @Override - public void init(final Map parameters) - { - super.init(parameters); - Node node = this.navigator.getDispatchContextNode(); - if (node == null) - { - throw new IllegalArgumentException("Edit Form wizard requires action node context."); - } - this.nodeRef = node.getNodeRef(); - - this.content = this.getContentService().getReader(nodeRef, ContentModel.PROP_CONTENT).getContentString(); - - this.fileName = (String)getNodeService().getProperty(nodeRef, ContentModel.PROP_NAME); // getName() ... - this.mimeType = MimetypeMap.MIMETYPE_XML; - } - - @Override - public String back() - { - return super.back(); - } - - @Override - protected void saveContent(File fileContent, String strContent) throws Exception - { - ContentWriter writer = getContentService().getWriter(nodeRef, ContentModel.PROP_CONTENT, true); - writer.putContent(strContent); - } - - @Override - protected String doPostCommitProcessing(FacesContext context, String outcome) - { - return outcome; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/content/EditSimpleWorkflowDialog.java b/war/src/main/java/org/alfresco/web/bean/content/EditSimpleWorkflowDialog.java deleted file mode 100644 index e9412b4086..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/content/EditSimpleWorkflowDialog.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.content; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.HashMap; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.actions.handlers.SimpleWorkflowHandler; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; - -public class EditSimpleWorkflowDialog extends BaseDialogBean -{ - - private static final long serialVersionUID = 7203447561571625990L; - - private static final String MSG_ERROR_UPDATE_SIMPLEWORKFLOW = "error_update_simpleworkflow"; - - protected Map workflowProperties; - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - saveWorkflow(); - return outcome; - } - - public boolean getFinishButtonDisabled() - { - return false; - } - - public Node getNode() - { - return this.browseBean.getDocument(); - } - - public Node getDocument() - { - return this.getNode(); - } - - public String saveWorkflow() - { - String outcome = "cancel"; - - try - { - Map updateProps = getNodeService().getProperties(getNode().getNodeRef()); - - // update the simple workflow properties - - // set the approve step name - updateProps.put(ApplicationModel.PROP_APPROVE_STEP, workflowProperties.get(SimpleWorkflowHandler.PROP_APPROVE_STEP_NAME)); - - // specify whether the approve step will copy or move the content - boolean approveMove = true; - String approveAction = (String) workflowProperties.get(SimpleWorkflowHandler.PROP_APPROVE_ACTION); - if (approveAction != null && approveAction.equals("copy")) - { - approveMove = false; - } - updateProps.put(ApplicationModel.PROP_APPROVE_MOVE, Boolean.valueOf(approveMove)); - - // create node ref representation of the destination folder - updateProps.put(ApplicationModel.PROP_APPROVE_FOLDER, workflowProperties.get(SimpleWorkflowHandler.PROP_APPROVE_FOLDER)); - - // determine whether there should be a reject step - boolean requireReject = true; - String rejectStepPresent = (String) workflowProperties.get(SimpleWorkflowHandler.PROP_REJECT_STEP_PRESENT); - if (rejectStepPresent != null && rejectStepPresent.equals("no")) - { - requireReject = false; - } - - if (requireReject) - { - // set the reject step name - updateProps.put(ApplicationModel.PROP_REJECT_STEP, workflowProperties.get(SimpleWorkflowHandler.PROP_REJECT_STEP_NAME)); - - // specify whether the reject step will copy or move the content - boolean rejectMove = true; - String rejectAction = (String) workflowProperties.get(SimpleWorkflowHandler.PROP_REJECT_ACTION); - if (rejectAction != null && rejectAction.equals("copy")) - { - rejectMove = false; - } - updateProps.put(ApplicationModel.PROP_REJECT_MOVE, Boolean.valueOf(rejectMove)); - - // create node ref representation of the destination folder - updateProps.put(ApplicationModel.PROP_REJECT_FOLDER, workflowProperties.get(SimpleWorkflowHandler.PROP_REJECT_FOLDER)); - } - else - { - // set all the reject properties to null to signify there should - // be no reject step - updateProps.put(ApplicationModel.PROP_REJECT_STEP, null); - updateProps.put(ApplicationModel.PROP_REJECT_MOVE, null); - updateProps.put(ApplicationModel.PROP_REJECT_FOLDER, null); - } - - // set the properties on the node - getNodeService().setProperties(getNode().getNodeRef(), updateProps); - getNode().reset(); - } - catch (Throwable e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), MSG_ERROR_UPDATE_SIMPLEWORKFLOW), e.getMessage()), e); - ReportedException.throwIfNecessary(e); - } - - return outcome; - } - - public Map getWorkflowProperties() - { - if (this.workflowProperties == null && getNode().hasAspect(ApplicationModel.ASPECT_SIMPLE_WORKFLOW)) - { - // get the exisiting properties for the node - Map props = getNode().getProperties(); - - String approveStepName = (String) props.get(ApplicationModel.PROP_APPROVE_STEP.toString()); - String rejectStepName = (String) props.get(ApplicationModel.PROP_REJECT_STEP.toString()); - - Boolean approveMove = (Boolean) props.get(ApplicationModel.PROP_APPROVE_MOVE.toString()); - Boolean rejectMove = (Boolean) props.get(ApplicationModel.PROP_REJECT_MOVE.toString()); - - NodeRef approveFolder = (NodeRef) props.get(ApplicationModel.PROP_APPROVE_FOLDER.toString()); - NodeRef rejectFolder = (NodeRef) props.get(ApplicationModel.PROP_REJECT_FOLDER.toString()); - - // put the workflow properties in a separate map for use by the JSP - this.workflowProperties = new HashMap(7); - this.workflowProperties.put(SimpleWorkflowHandler.PROP_APPROVE_STEP_NAME, approveStepName); - this.workflowProperties.put(SimpleWorkflowHandler.PROP_APPROVE_ACTION, approveMove ? "move" : "copy"); - this.workflowProperties.put(SimpleWorkflowHandler.PROP_APPROVE_FOLDER, approveFolder); - - if (rejectStepName == null || rejectMove == null || rejectFolder == null) - { - this.workflowProperties.put(SimpleWorkflowHandler.PROP_REJECT_STEP_PRESENT, "no"); - } - else - { - this.workflowProperties.put(SimpleWorkflowHandler.PROP_REJECT_STEP_PRESENT, "yes"); - this.workflowProperties.put(SimpleWorkflowHandler.PROP_REJECT_STEP_NAME, rejectStepName); - this.workflowProperties.put(SimpleWorkflowHandler.PROP_REJECT_ACTION, rejectMove ? "move" : "copy"); - this.workflowProperties.put(SimpleWorkflowHandler.PROP_REJECT_FOLDER, rejectFolder); - } - } - - return this.workflowProperties; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/content/InviteContentUsersWizard.java b/war/src/main/java/org/alfresco/web/bean/content/InviteContentUsersWizard.java deleted file mode 100644 index 8905094586..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/content/InviteContentUsersWizard.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.content; - -import java.util.Set; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.wizard.BaseInviteUsersWizard; - -/** - * Concrete implementation providing the ability to invite users to content. - * - * @author gavinc - */ -public class InviteContentUsersWizard extends BaseInviteUsersWizard -{ - private static final long serialVersionUID = 9198783146031469545L; - - @Override - protected Set getPermissionsForType() - { - // Let the permission service do the caching to allow for dynamic model updates, etc. - return this.permissionService.getSettablePermissions(getNode().getType()); - } - - @Override - protected Node getNode() - { - return this.browseBean.getDocument(); - } - - @Override - protected String getEmailTemplateXPath() - { - FacesContext fc = FacesContext.getCurrentInstance(); - String xpath = Application.getRootPath(fc) + "/" + - Application.getGlossaryFolderName(fc) + "/" + - Application.getEmailTemplatesFolderName(fc) + "/" + - Application.getNotifyEmailTemplatesFolderName(fc) + "//*"; - return xpath; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/content/SetContentPropertiesDialog.java b/war/src/main/java/org/alfresco/web/bean/content/SetContentPropertiesDialog.java deleted file mode 100644 index 6207148222..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/content/SetContentPropertiesDialog.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.content; - -import org.alfresco.web.app.AlfrescoNavigationHandler; - -/** - * Bean implementation of the "Set Content Properties" dialog. - * - * @author gavinc - */ -public class SetContentPropertiesDialog extends EditContentPropertiesDialog -{ - private static final long serialVersionUID = -7705362669371767349L; - - @Override - protected String getDefaultCancelOutcome() - { - return super.getDefaultCancelOutcome() + - AlfrescoNavigationHandler.OUTCOME_SEPARATOR + - "browse"; - } - - @Override - protected String getDefaultFinishOutcome() - { - return super.getDefaultFinishOutcome() + - AlfrescoNavigationHandler.OUTCOME_SEPARATOR + - "browse"; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/content/VersionedDocumentDetailsDialog.java b/war/src/main/java/org/alfresco/web/bean/content/VersionedDocumentDetailsDialog.java deleted file mode 100644 index 25e2f91b86..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/content/VersionedDocumentDetailsDialog.java +++ /dev/null @@ -1,602 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.content; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.web.scripts.FileTypeImageUtils; -import org.alfresco.service.cmr.ml.ContentFilterLanguagesService; -import org.alfresco.service.cmr.ml.EditionService; -import org.alfresco.service.cmr.ml.MultilingualContentService; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.version.Version; -import org.alfresco.service.cmr.version.VersionHistory; -import org.alfresco.service.cmr.version.VersionService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.servlet.DownloadContentServlet; -import org.alfresco.web.bean.BrowseBean; -import org.alfresco.web.bean.repository.MapNode; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.springframework.extensions.surf.util.I18NUtil; -import org.springframework.extensions.surf.util.ParameterCheck; - -/** - * Bean with generic function helping the rendering of the versioned properties - * - * @author Yanick Pignot - */ -public class VersionedDocumentDetailsDialog implements Serializable -{ - private static final long serialVersionUID = 1575175076564595262L; - - /** Dependencies */ - transient private VersionService versionService; - transient private EditionService editionService; - transient private NodeService nodeService; - transient private MultilingualContentService multilingualContentService; - transient private ContentFilterLanguagesService contentFilterLanguagesService; - - /** Determine if the version is a translation of a old edition */ - private boolean fromPreviousEditon; - - /** The version selected by the user */ - private Version documentVersion; - private VersionHistory versionHistory; - - /** The multilingual information of the selected version selected by the user */ - private Version documentEdition; - private VersionHistory editionHistory; - - /** Common property resolvers accessed from the BrowseBean */ - private BrowseBean browseBean; - - - public void init() - { - fromPreviousEditon = false; - documentVersion = null; - versionHistory = null; - documentEdition = null; - editionHistory = null; - } - - /** - * @param browseBean The BrowseBean to set. - */ - public void setBrowseBean(BrowseBean browseBean) - { - this.browseBean = browseBean; - } - - /** - * Set which version of the current node that the user want to display the properties - */ - public void setBrowsingVersion(ActionEvent event) - { - init(); - - // Get the properties of the action event - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - - String versionLabel = params.get("versionLabel"); - String id = params.get("id"); - String lang = params.get("lang"); - - setBrowsingVersion(id, versionLabel, lang); - } - - - /** - * Implementation of setBrowsingVersion action event to be use with the needed parameters. - */ - private void setBrowsingVersion(String id, String versionLabel, String lang) - { - // test if the mandatories parameter are valid - ParameterCheck.mandatoryString("The id of the node", id); - ParameterCheck.mandatoryString("The version of the node", versionLabel); - - try - { - // try to get the nodeRef with the given ID. This node is not a versioned node. - NodeRef currentNodeRef = new NodeRef(Repository.getStoreRef(), id); - - // the threatment is different if the node is a translation or a mlContainer - if(getNodeService().getType(currentNodeRef).equals(ContentModel.TYPE_MULTILINGUAL_CONTAINER)) - { - // test if the lang parameter is valid - ParameterCheck.mandatoryString("The lang of the node", lang); - - fromPreviousEditon = true; - - versionLabel = cleanVersionLabel(versionLabel); - - // set the edition information of the mlContainer of the selected translation version - this.editionHistory = getEditionService().getEditions(currentNodeRef); - this.documentEdition = editionHistory.getVersion(versionLabel); - - // set the version to display - this.documentVersion = getBrowsingVersionForMLContainer(currentNodeRef, versionLabel, lang); - } - else - { - fromPreviousEditon = false; - - // set the version history - this.versionHistory = getVersionService().getVersionHistory(currentNodeRef); - // set the version to display - this.documentVersion = getBrowsingVersionForDocument(currentNodeRef, versionLabel); - } - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {id}) ); - } - } - - /** - * Navigates to next item in the list of versioned content for the current VersionHistory - */ - public void nextItem(ActionEvent event) - { - // Get the properties of the action event - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - - String versionLabel = params.get("versionLabel"); - - // if the version is not specified, get the next version - if(versionLabel == null) - { - List nextVersions = new ArrayList(this.versionHistory.getSuccessors(this.documentVersion)); - - // if the version history doesn't contains successor, get the root version (the first one) - if(nextVersions == null || nextVersions.size() < 1) - { - this.documentVersion = versionHistory.getRootVersion(); - } - else - { - this.documentVersion = nextVersions.get(0); - } - } - else - { - this.documentVersion = this.versionHistory.getVersion(versionLabel); - } - } - - /** - * Navigates to previous item in the list of versioned content for the current VersionHistory - */ - public void previousItem(ActionEvent event) - { - // Get the properties of the action event - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - - String versionLabel = params.get("versionLabel"); - - // if the version is not specified, get the next version - if(versionLabel == null) - { - Version prevVersion = this.versionHistory.getPredecessor(this.documentVersion); - - // if the version history doesn't contains predecessor, get the last version (ie. most recent) - if(prevVersion == null) - { - List allVersions = new ArrayList(this.versionHistory.getAllVersions()); - this.documentVersion = allVersions.get(0); - } - else - { - this.documentVersion = prevVersion; - } - } - else - { - this.documentVersion = this.versionHistory.getVersion(versionLabel); - } - } - - /** - * Returns a list of objects representing the translations of the given version of the mlContainer - * - * @return List of translations - */ - @SuppressWarnings("unchecked") - public List getTranslations() - { - // get the version of the mlContainer and its translations - List translationsList = getEditionService().getVersionedTranslations(this.documentEdition); - - Map translationNodeRef; - - // if translation size == 0, the edition is the current edition and the translations are not yet attached. - if(translationsList.size() == 0) - { - // the selection edition is the current: use the multilingual content service - translationNodeRef = getMultilingualContentService().getTranslations(this.documentEdition.getVersionedNodeRef()); - } - else - { - translationNodeRef = new HashMap(translationsList.size()); - - // get the last (most recent) version of the translation in the given lang of the edition - for (VersionHistory history : translationsList) - { - // get the list of versions (in descending order - ie. most recent first) - List orderedVersions = new ArrayList(history.getAllVersions()); - - // the last (most recent) version is the first version of the list - Version lastVersion = orderedVersions.get(0); - - // fill the list of translation - if(lastVersion != null) - { - NodeRef versionNodeRef = lastVersion.getFrozenStateNodeRef(); - Locale locale = (Locale) getNodeService().getProperty(versionNodeRef, ContentModel.PROP_LOCALE); - translationNodeRef.put(locale, versionNodeRef); - } - } - } - - // the list of client-side translation to return - List translations = new ArrayList(translationNodeRef.size()); - - for (Map.Entry entry : translationNodeRef.entrySet()) - { - Locale locale = entry.getKey(); - NodeRef nodeRef = entry.getValue(); - - // create a map node representation of the translation - MapNode mapNode = new MapNode(nodeRef); - - String lgge = (locale != null) ? - // convert the locale into new ISO codes - getContentFilterLanguagesService().convertToNewISOCode(locale.getLanguage()).toUpperCase() - : null; - - mapNode.put("name", getNodeService().getProperty(nodeRef, ContentModel.PROP_NAME)); - mapNode.put("language", lgge); - mapNode.put("url", DownloadContentServlet.generateBrowserURL(nodeRef, mapNode.getName())); - - mapNode.put("notEmpty", new Boolean(!getNodeService().hasAspect(nodeRef, ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION))); - - // add the client side version to the list - translations.add(mapNode); - - } - - return translations; - } - - - /** - * Returns a list of objects representing the versions of the - * current document - * - * @return List of previous versions - */ - public List getVersionHistory() - { - List versions = new ArrayList(); - - for (Version version : this.versionHistory.getAllVersions()) - { - // create a map node representation of the version - MapNode clientVersion = new MapNode(version.getFrozenStateNodeRef()); - clientVersion.put("versionLabel", version.getVersionLabel()); - clientVersion.put("notes", version.getDescription()); - clientVersion.put("author", version.getCreator()); - clientVersion.put("versionDate", version.getCreatedDate()); - - if(getFrozenStateDocument().hasAspect(ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION)) - { - clientVersion.put("url", null); - } - else - { - clientVersion.put("url", DownloadContentServlet.generateBrowserURL(version.getFrozenStateNodeRef(), - clientVersion.getName())); - } - - // add the client side version to the list - versions.add(clientVersion); - } - - return versions; - } - - /** - * @return true if the version is a translation of a previous edition - */ - public boolean isFromPreviousEditon() - { - return fromPreviousEditon; - } - - /** - * Returns the URL to download content for the current document - * - * @return Content url to download the current document - */ - public String getUrl() - { - return DownloadContentServlet.generateBrowserURL(getFrozenStateNodeRef(), getName()); - } - - /** - * @return the versioned node selected by the user - */ - public Node getFrozenStateDocument() - { - Node node = new Node(getFrozenStateNodeRef()); - node.addPropertyResolver("mimetype", this.browseBean.resolverMimetype); - node.addPropertyResolver("encoding", this.browseBean.resolverEncoding); - node.addPropertyResolver("size", this.browseBean.resolverSize); - return node; - } - - /** - * @return the versioned node ref selected by the user - */ - public NodeRef getFrozenStateNodeRef() - { - return documentVersion.getFrozenStateNodeRef(); - } - - /** - * @return the edition of the mlContainer of the selected verion of the translation - */ - public Node getMultilingualContainerDocument() - { - return new Node(documentEdition.getFrozenStateNodeRef()); - } - - /** - * @return the name of selected version - */ - public String getName() - { - String name = (String)getNodeService().getProperty(getFrozenStateNodeRef(), ContentModel.PROP_NAME); - return name; - } - - /** - * @return the file type image URL of the version - */ - public String getFileType32() - { - String fileType = FileTypeImageUtils.getFileTypeImage(getName(), false); - return fileType; - } - - public boolean isEmptyTranslation() - { - return getNodeService().hasAspect(getFrozenStateNodeRef(), ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION); - } - - /** - * @return the version to display of the document selected by the user - */ - public Version getVersion() - { - return this.documentVersion; - } - - /** - * @return the next page to display according to which page the dialog is coming from - */ - public String getOutcome() - { - return (this.fromPreviousEditon) ? "dialog:showMLContainerDetails" : "dialog:showDocDetails"; - } - - /** - * Util method which remove the eventual '(actual)' label from the version label. - */ - private String cleanVersionLabel(String versionLabel) - { - // remove the (actual vesrion) label if needed - int idx = versionLabel.indexOf(' '); - if(idx > -1) - { - versionLabel = versionLabel.substring(0, idx); - } - return versionLabel; - } - - /** - * Util method which returns the given version of a node - */ - private Version getBrowsingVersionForDocument(NodeRef document, String versionLabel) - { - return this.getVersionService().getVersionHistory(document).getVersion(versionLabel); - } - - /** - * Util method which returns the current version of a node - */ - private Version getBrowsingCurrentVersionForMLContainer(NodeRef document, String lang) - { - NodeRef translation = getMultilingualContentService().getTranslationForLocale(document, I18NUtil.parseLocale(lang)); - this.versionHistory = getVersionService().getVersionHistory(translation); - - return getVersionService().getCurrentVersion(translation); - } - - /** - * Util method which return the last (most recent) version of a translation of a given edition of a mlContainer according its language - */ - @SuppressWarnings("unchecked") - private Version getBrowsingVersionForMLContainer(NodeRef document, String editionLabel, String lang) - { - // get the list of translations of the given edition of the mlContainer - List translations = getEditionService().getVersionedTranslations(this.documentEdition); - - // if translation size == 0, the edition is the current edition and the translations are not yet attached. - if(translations.size() == 0) - { - // the selection edition is the current. - return getBrowsingCurrentVersionForMLContainer(document, lang); - } - else - { - Version versionToReturn = null; - - // get the last (most recent) version of the translation in the given lang of the edition - for (VersionHistory history : translations) - { - // get the list of versions (in descending order - ie. most recent first) - List orderedVersions = new ArrayList(history.getAllVersions()); - - // the last version (ie. most recent) is the first version of the list - Version lastVersion = orderedVersions.get(0); - - if(lastVersion != null) - { - Map properties = getEditionService().getVersionedMetadatas(lastVersion); - Locale locale = (Locale) properties.get(ContentModel.PROP_LOCALE); - - if(locale.getLanguage().equalsIgnoreCase(lang)) - { - versionToReturn = lastVersion; - this.versionHistory = history; - break; - } - } - } - return versionToReturn; - } - - } - - - /** - * @param versionService the Version Service to set - */ - public void setVersionService(VersionService versionService) - { - this.versionService = versionService; - } - - protected VersionService getVersionService() - { - if (versionService == null) - { - versionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getVersionService(); - } - return versionService; - } - - /** - * @param editionService the Edition Service to set - */ - public void setEditionService(EditionService editionService) - { - this.editionService = editionService; - } - - protected EditionService getEditionService() - { - if (editionService == null) - { - editionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getEditionService(); - } - return editionService; - } - - /** - * @param nodeService the Node Service to set - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - protected NodeService getNodeService() - { - if (nodeService == null) - { - nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - } - return nodeService; - } - - /** - * @param contentFilterLanguagesService the Content Filter Languages Service to set - */ - public void setContentFilterLanguagesService(ContentFilterLanguagesService contentFilterLanguagesService) - { - this.contentFilterLanguagesService = contentFilterLanguagesService; - } - - protected ContentFilterLanguagesService getContentFilterLanguagesService() - { - if (contentFilterLanguagesService == null) - { - contentFilterLanguagesService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getContentFilterLanguagesService(); - } - return contentFilterLanguagesService; - } - - /** - * @param multilingualContentService Content Service the Multilingual Content Service to set - */ - public void setMultilingualContentService(MultilingualContentService multilingualContentService) - { - this.multilingualContentService = multilingualContentService; - } - - protected MultilingualContentService getMultilingualContentService() - { - if (multilingualContentService == null) - { - multilingualContentService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getMultilingualContentService(); - } - return multilingualContentService; - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/bean/content/ViewContentPropertiesDialog.java b/war/src/main/java/org/alfresco/web/bean/content/ViewContentPropertiesDialog.java deleted file mode 100644 index b54d16d6a5..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/content/ViewContentPropertiesDialog.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.content; - -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.repository.ContentData; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.Utils; - -/** - * Bean implementation of the "View Content Properties" dialog. - * - * @author gavinc - */ -public class ViewContentPropertiesDialog extends BaseDialogBean -{ - private static final long serialVersionUID = -867609607881256449L; - - protected static final String TEMP_PROP_MIMETYPE = "mimetype"; - protected static final String TEMP_PROP_ENCODING = "encoding"; - - protected Node viewingNode; - - // ------------------------------------------------------------------------------ - // Dialog implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - Node document = this.browseBean.getDocument(); - if(document != null) - { - - // setup the editable node - this.viewingNode = new Node(document.getNodeRef()); - - - // special case for Mimetype - since this is a sub-property of the ContentData object - // we must extract it so it can be edited in the client, then we check for it later - // and create a new ContentData object to wrap it and it's associated URL - ContentData content = (ContentData)this.viewingNode.getProperties().get(ContentModel.PROP_CONTENT); - if (content != null) - { - this.viewingNode.getProperties().put(TEMP_PROP_MIMETYPE, content.getMimetype()); - this.viewingNode.getProperties().put(TEMP_PROP_ENCODING, content.getEncoding()); - } - - // add the specially handled 'size' property - this.viewingNode.addPropertyResolver("size", this.browseBean.resolverSize); - } - } - - @Override - protected String finishImpl(FacesContext context, String outcome) - throws Exception - { - // nothing to do as the finish button is not shown and the dialog is read only - - return outcome; - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "close"); - } - - // ------------------------------------------------------------------------------ - // Bean getters and setters - - /** - * Returns the node being viewed - * - * @return The node being viewed - */ - public Node getViewingNode() - { - return this.viewingNode; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/dashboard/DashboardManager.java b/war/src/main/java/org/alfresco/web/bean/dashboard/DashboardManager.java deleted file mode 100644 index 92c4988d9e..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/dashboard/DashboardManager.java +++ /dev/null @@ -1,433 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.dashboard; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -import javax.faces.context.FacesContext; - -import org.springframework.extensions.config.ConfigService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.PreferencesService; -import org.alfresco.web.config.DashboardsConfigElement; -import org.alfresco.web.config.DashboardsConfigElement.DashletDefinition; -import org.alfresco.web.config.DashboardsConfigElement.LayoutDefinition; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean that manages the Dashboard framework. - * - * @author Kevin Roast - */ -public class DashboardManager implements Serializable -{ - private static final long serialVersionUID = 6160628072764689380L; - - public static final String BEAN_NAME = "DashboardManager"; - - private static Log logger = LogFactory.getLog(DashboardManager.class); - - private static final String PREF_DASHBOARD = "dashboard"; - private static final String LAYOUT_DEFAULT = "default"; - private static final String DASHLET_STARTEDDEFAULT = "getting-started"; - private static final String DASHLET_TASKSDEFAULT = "tasks-todo"; - - private static final String JSP_DUMMY = "/jsp/dashboards/dummy.jsp"; - - private PageConfig pageConfig = null; - transient private DashletRenderingList renderingList = null; - transient private DashletTitleList titleList = null; - - /** - * @return The layout JSP page for the current My Alfresco dashboard page - */ - public String getLayoutPage() - { - String layout = null; - Page page = getPageConfig().getCurrentPage(); - if (page != null) - { - layout = page.getLayoutDefinition().JSPPage; - } - return layout; - } - - /** - * Helper to init the dashboard for display - */ - public void initDashboard() - { - this.renderingList = null; - this.titleList = null; - } - - /** - * @return JSF List getter to return which dashlets are available for rendering - */ - public List getDashletAvailable() - { - if (this.renderingList == null) - { - this.renderingList = new DashletRenderingList(getPageConfig()); - } - return this.renderingList; - } - - /** - * @return JSF List getter to return dashlet title strings - */ - public List getDashletTitle() - { - if (this.titleList == null) - { - this.titleList = new DashletTitleList(getPageConfig()); - } - return this.titleList; - } - - /** - * Return the JSP for the specified dashlet index - * - * @param index Zero based index from the left most column working top-bottom then left-right - * - * @return JSP page for the dashlet or a blank dummy page if not found - */ - public String getDashletPage(int index) - { - String page = JSP_DUMMY; - DashletDefinition def = getDashletDefinitionByIndex(getPageConfig(), index); - if (def != null) - { - page = def.JSPPage; - } - return page; - } - - /** - * @return the PageConfig for the current My Alfresco dashboard page - */ - public PageConfig getPageConfig() - { - if (this.pageConfig == null) - { - PageConfig pageConfig; - - DashboardsConfigElement config = getDashboardConfig(); - - // read the config for this user from the Preferences - String xml = (String)PreferencesService.getPreferences().getValue(PREF_DASHBOARD); - if (xml != null && xml.length() != 0) - { - if (logger.isDebugEnabled()) - logger.debug("PageConfig found: " + xml); - - // process the XML config and convert into a PageConfig object - pageConfig = new PageConfig(); - pageConfig.fromXML(config, xml); - } - else - { - if (logger.isDebugEnabled()) - logger.debug("No PageConfig found, creating default instance."); - - // create default config for the first access for a user - pageConfig = new PageConfig(); - LayoutDefinition layout = config.getLayoutDefinition(LAYOUT_DEFAULT); - if (layout != null) - { - Page page = new Page("default", layout); - Column defaultColumn = new Column(); - - // add the default dashlet(s) to the column as specified in the config - if (config.getDefaultDashlets() != null) - { - for (String id : config.getDefaultDashlets()) - { - DashletDefinition dashlet = config.getDashletDefinition(id); - if (dashlet != null) - { - defaultColumn.addDashlet(dashlet); - } - } - } - - // add the column to the page and we are done - page.addColumn(defaultColumn); - pageConfig.addPage(page); - } - } - - this.pageConfig = pageConfig; - } - - return this.pageConfig; - } - - /** - * Persist the supplied PageConfig for the current user - */ - public void savePageConfig(PageConfig config) - { - this.pageConfig = config; - - // reset cached values - initDashboard(); - - // persist the changes - PreferencesService.getPreferences().setValue(PREF_DASHBOARD, this.pageConfig.toXML()); - } - - /** - * @return The externally configured WebClient config element for the Dashboards - */ - public static DashboardsConfigElement getDashboardConfig() - { - ConfigService service = Application.getConfigService(FacesContext.getCurrentInstance()); - DashboardsConfigElement config = (DashboardsConfigElement)service.getConfig("Dashboards").getConfigElement( - DashboardsConfigElement.CONFIG_ELEMENT_ID); - return config; - } - - /** - * Helper to get the DashDefinition as the zero based index, working from the left most column - * top-bottom then working left-right. - * - * @param index Zero based index from the left most column working top-bottom then left-right - * - * @return DashletDefinition if found or null if no dashlet at the specified index - */ - private static DashletDefinition getDashletDefinitionByIndex(PageConfig config, int index) - { - DashletDefinition def = null; - - LayoutDefinition layoutDef = config.getCurrentPage().getLayoutDefinition(); - List columns = config.getCurrentPage().getColumns(); - int columnCount = columns.size(); - int selectedColumn = index / layoutDef.ColumnLength; - if (selectedColumn < columnCount) - { - List dashlets = columns.get(selectedColumn).getDashlets(); - if (index % layoutDef.ColumnLength < dashlets.size()) - { - def = dashlets.get(index % layoutDef.ColumnLength); - } - } - if (logger.isDebugEnabled()) - logger.debug("Searching for dashlet at index: " + index + - " and found " + (def != null ? def.JSPPage : null)); - - return def; - } - - - /** - * Dashlet rendering list. - * - * Returns true from the get() method if the specified dashlet is available for rendering. - */ - private static class DashletRenderingList extends JSFHelperList - { - private static final long serialVersionUID = -8611864902847833088L; - - PageConfig config; - - public DashletRenderingList(PageConfig config) - { - this.config = config; - } - - /** - * @see java.util.List#get(int) - */ - public Object get(int index) - { - return getDashletDefinitionByIndex(config, index) != null; - } - } - - /** - * Dashlet title list. - * - * Returns the title string from the get() method if the specified dashlet is available. - */ - private static class DashletTitleList extends JSFHelperList - { - private static final long serialVersionUID = 3522065600475233262L; - - PageConfig config; - - public DashletTitleList(PageConfig config) - { - this.config = config; - } - - /** - * @see java.util.List#get(int) - */ - public Object get(int index) - { - String result = ""; - - DashletDefinition def = getDashletDefinitionByIndex(config, index); - if (def != null) - { - if (def.LabelId != null) - { - result = Application.getMessage(FacesContext.getCurrentInstance(), def.LabelId); - } - else if (def.Label != null) - { - result = def.Label; - } - } - - return result; - } - } - - /** - * Helper class that implements a dummy List contract for use by JSF List getter methods - */ - private static abstract class JSFHelperList implements List, Serializable - { - // - // Satisfy List interface contract - // - - public void add(int arg0, Object arg1) - { - } - - public boolean add(Object arg0) - { - return false; - } - - public boolean addAll(Collection arg0) - { - return false; - } - - public boolean addAll(int arg0, Collection arg1) - { - return false; - } - - public void clear() - { - } - - public boolean contains(Object arg0) - { - return false; - } - - public boolean containsAll(Collection arg0) - { - return false; - } - - public int indexOf(Object arg0) - { - return 0; - } - - public boolean isEmpty() - { - return false; - } - - public Iterator iterator() - { - return null; - } - - public int lastIndexOf(Object arg0) - { - return 0; - } - - public ListIterator listIterator() - { - return null; - } - - public ListIterator listIterator(int arg0) - { - return null; - } - - public Object remove(int arg0) - { - return null; - } - - public boolean remove(Object arg0) - { - return false; - } - - public boolean removeAll(Collection arg0) - { - return false; - } - - public boolean retainAll(Collection arg0) - { - return false; - } - - public Object set(int arg0, Object arg1) - { - return null; - } - - public int size() - { - return 0; - } - - public List subList(int arg0, int arg1) - { - return null; - } - - public Object[] toArray() - { - return null; - } - - public Object[] toArray(Object[] arg0) - { - return null; - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/dashboard/DashboardWizard.java b/war/src/main/java/org/alfresco/web/bean/dashboard/DashboardWizard.java deleted file mode 100644 index 96ca80141a..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/dashboard/DashboardWizard.java +++ /dev/null @@ -1,497 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.dashboard; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.faces.component.UISelectMany; -import javax.faces.component.UISelectOne; -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.faces.model.SelectItem; - -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.wizard.BaseWizardBean; -import org.alfresco.web.config.DashboardsConfigElement; -import org.alfresco.web.config.DashboardsConfigElement.DashletDefinition; -import org.alfresco.web.config.DashboardsConfigElement.LayoutDefinition; -import org.alfresco.web.ui.common.component.UIListItem; -import org.alfresco.web.ui.common.component.description.UIDescription; - -/** - * @author Kevin Roast - */ -public class DashboardWizard extends BaseWizardBean -{ - private static final long serialVersionUID = 2544040677742418309L; - - private static final String COMPONENT_COLUMNDASHLETS = "column-dashlets"; - - private static final String COMPONENT_ALLDASHLETS = "all-dashlets"; - - private static final String MSG_COLUMN = "dashboard_column"; - - /** List of icons items to display as selectable Layout definitions */ - private List layoutIcons = null; - - /** List of descriptions of the layouts */ - private List layoutDescriptions = null; - - /** List of SelectItem objects representing the available dashlets */ - private List dashlets = null; - - /** Currently selected layout */ - private String layout; - - /** Currently selected column to edit */ - private int column; - - /** The PageConfig holding the columns/dashlets during editing */ - private PageConfig editConfig; - - /** The DashboardManager instance */ - private DashboardManager dashboardManager; - - - // ------------------------------------------------------------------------------ - // Bean setters - - /** - * @param dashboardManager The dashboardManager to set. - */ - public void setDashboardManager(DashboardManager dashboardManager) - { - this.dashboardManager = dashboardManager; - } - - - // ------------------------------------------------------------------------------ - // Wizard implementation - - /** - * @see org.alfresco.web.bean.dialog.BaseDialogBean#init(java.util.Map) - */ - public void init(Map parameters) - { - super.init(parameters); - - this.editConfig = new PageConfig(this.dashboardManager.getPageConfig()); - this.layout = this.editConfig.getCurrentPage().getLayoutDefinition().Id; - this.column = 0; - } - - /** - * @see org.alfresco.web.bean.dialog.BaseDialogBean#finishImpl(javax.faces.context.FacesContext, java.lang.String) - */ - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - this.dashboardManager.savePageConfig(this.editConfig); - return outcome; - } - - /** - * @return Returns the summary data for the wizard. - */ - public String getSummary() - { - LayoutDefinition def = DashboardManager.getDashboardConfig().getLayoutDefinition(this.layout); - String label = def.Label; - if (label == null) - { - label = Application.getMessage(FacesContext.getCurrentInstance(), def.LabelId); - } - return buildSummary( - new String[]{Application.getMessage(FacesContext.getCurrentInstance(),"step_layout")}, - new String[]{label}); - } - - - // ------------------------------------------------------------------------------ - // Dashboard Wizard bean getters - - /** - * @return true to allow the Guest user to configure the dashboard, false otherwise - */ - public boolean getAllowGuestConfig() - { - return DashboardManager.getDashboardConfig().getAllowGuestConfig(); - } - - /** - * @return The currently selected layout ID - used by the Dynamic Description component - */ - public String getLayout() - { - return this.layout; - } - - /** - * Set the currently selected layout ID - */ - public void setLayout(String layout) - { - this.layout = layout; - LayoutDefinition def = DashboardManager.getDashboardConfig().getLayoutDefinition(layout); - this.editConfig.getCurrentPage().setLayoutDefinition(def); - if (this.column >= def.Columns) - { - this.column = def.Columns - 1; - } - } - - /** - * @return the number of columns in the selected page layout - */ - public int getColumnCount() - { - return DashboardManager.getDashboardConfig().getLayoutDefinition(getLayout()).Columns; - } - - /** - * @return the number of components per column supported in the selected page layout - */ - public int getColumnMax() - { - return DashboardManager.getDashboardConfig().getLayoutDefinition(getLayout()).ColumnLength; - } - - /** - * @return the array of UI select items representing the columns that can be configured - */ - public SelectItem[] getColumns() - { - FacesContext fc = FacesContext.getCurrentInstance(); - LayoutDefinition layoutDef = DashboardManager.getDashboardConfig().getLayoutDefinition(getLayout()); - SelectItem[] columns = new SelectItem[layoutDef.Columns]; - for (int i=0; i getAllDashlets() - { - if ((this.dashlets == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - FacesContext fc = FacesContext.getCurrentInstance(); - DashboardsConfigElement config = DashboardManager.getDashboardConfig(); - Collection dashletDefs = config.getDashlets(); - List dashlets = new ArrayList(dashletDefs.size()); - for (DashletDefinition dashletDef : dashletDefs) - { - String label = dashletDef.Label; - if (label == null) - { - label = Application.getMessage(fc, dashletDef.LabelId); - } - String description = dashletDef.Description; - if (description == null) - { - description = Application.getMessage(fc, dashletDef.DescriptionId); - } - if (description != null) - { - // append description of the dashlet if set - label = label + " (" + description + ')'; - } - SelectItem item = new SelectItem(dashletDef.Id, label); - dashlets.add(item); - } - this.dashlets = dashlets; - } - return this.dashlets; - } - - /** - * @return the List of SelectItem objects representing the dashlets displayed in the - * currently selected column. - */ - public List getColumnDashlets() - { - FacesContext fc = FacesContext.getCurrentInstance(); - - Column column = this.editConfig.getCurrentPage().getColumns().get(this.column); - // trim the max number of dashlets for this column - LayoutDefinition layoutDef = this.editConfig.getCurrentPage().getLayoutDefinition(); - column.trimDashlets(layoutDef.ColumnLength); - List dashlets = new ArrayList(column.getDashlets().size()); - for (DashletDefinition dashletDef : column.getDashlets()) - { - String label = dashletDef.Label; - if (label == null) - { - label = Application.getMessage(fc, dashletDef.LabelId); - } - dashlets.add(new SelectItem(dashletDef.Id, label)); - } - return dashlets; - } - - /** - * @return the number of dashlets currently displayed in the selected column - */ - public int getColumnDashletCount() - { - Column column = this.editConfig.getCurrentPage().getColumns().get(this.column); - return column.getDashlets().size(); - } - - /** - * @return List of UIDescription objects for the available layouts - */ - public List getLayoutDescriptions() - { - if ((this.layoutDescriptions == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - buildLayoutValueLists(); - } - return this.layoutDescriptions; - } - - /** - * @return the List of UIListItem objects representing the Layout icons - */ - public List getLayoutIcons() - { - if ((this.layoutIcons == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - buildLayoutValueLists(); - } - return this.layoutIcons; - } - - /** - * Build the cached list of values for the layout page. The lists are used by the - * image radio picker and dynamic description components. - */ - private void buildLayoutValueLists() - { - List icons = new ArrayList(4); - List descriptions = new ArrayList(4); - - FacesContext context = FacesContext.getCurrentInstance(); - - DashboardsConfigElement config = DashboardManager.getDashboardConfig(); - Iterator layoutItr = config.getLayouts().iterator(); - while (layoutItr.hasNext()) - { - LayoutDefinition layoutDef = layoutItr.next(); - - // build UIListItem to represent the layout image - String label = layoutDef.Label; - if (label == null) - { - label = Application.getMessage(context, layoutDef.LabelId); - } - String desc = layoutDef.Description; - if (desc == null) - { - desc = Application.getMessage(context, layoutDef.DescriptionId); - } - UIListItem item = new UIListItem(); - item.setLabel(label); - item.setTooltip(desc); - item.setValue(layoutDef.Id); - item.setImage(layoutDef.Image); - icons.add(item); - - // build UIDescription to represent the layout description text - UIDescription description = new UIDescription(); - description.setControlValue(layoutDef.Id); - description.setText(desc); - descriptions.add(description); - } - - this.layoutIcons = icons; - this.layoutDescriptions = descriptions; - } - - /** - * Action event handler called to Add dashlets to the selection for a column - */ - public void addDashlets(ActionEvent event) - { - UISelectMany dashletPicker = (UISelectMany)event.getComponent().findComponent(COMPONENT_ALLDASHLETS); - UISelectOne dashletColumn = (UISelectOne)event.getComponent().findComponent(COMPONENT_COLUMNDASHLETS); - - // get the IDs of the selected Dashlet definitions - Object[] selected = dashletPicker.getSelectedValues(); - - if (selected.length != 0) - { - // get the column to add the dashlets too - DashboardsConfigElement config = DashboardManager.getDashboardConfig(); - LayoutDefinition layoutDef = this.editConfig.getCurrentPage().getLayoutDefinition(); - Column column = this.editConfig.getCurrentPage().getColumns().get(this.column); - - // add each selected dashlet to the column - for (int i=0; i. - * #L% - */ -package org.alfresco.web.bean.dashboard; - -import java.io.Serializable; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.NavigationBean; - -/** - * Backing bean for the Getting Started Dashlet page. - * - * @author Kevin Roast - */ -public class GettingStartedBean implements Serializable -{ - private static final long serialVersionUID = 5170536816906380802L; - - private NavigationBean navigationBean; - - - /** - * @param navigationBean The navigationBean to set. - */ - public void setNavigationBean(NavigationBean navigationBean) - { - this.navigationBean = navigationBean; - } - - public String browseHomeSpace() - { - this.navigationBean.setCurrentNodeId(getHomeSpaceId()); - return "browse"; - } - - public String createSpace() - { - this.navigationBean.setCurrentNodeId(getHomeSpaceId()); - return "dialog:createSpace"; - } - - public String createContent() - { - this.navigationBean.setCurrentNodeId(getHomeSpaceId()); - return "wizard:createContent"; - } - - public String addContent() - { - this.navigationBean.setCurrentNodeId(getHomeSpaceId()); - return "dialog:addContent"; - } - - private String getHomeSpaceId() - { - return Application.getCurrentUser(FacesContext.getCurrentInstance()).getHomeSpaceId(); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/dashboard/PageConfig.java b/war/src/main/java/org/alfresco/web/bean/dashboard/PageConfig.java deleted file mode 100644 index 02936a5351..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/dashboard/PageConfig.java +++ /dev/null @@ -1,424 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.dashboard; - -import java.io.Serializable; -import java.io.StringReader; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.web.config.DashboardsConfigElement; -import org.alfresco.web.config.DashboardsConfigElement.DashletDefinition; -import org.alfresco.web.config.DashboardsConfigElement.LayoutDefinition; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.DocumentHelper; -import org.dom4j.Element; -import org.dom4j.io.OutputFormat; -import org.dom4j.io.SAXReader; -import org.dom4j.io.XMLWriter; - -/** - * Describes the config for the Pages in a user Dashboard. - * Multiple Pages are supported. - * - * @author Kevin Roast - */ -public final class PageConfig implements Serializable -{ - private static final long serialVersionUID = 5464324390924278215L; - - private static Log logger = LogFactory.getLog(DashboardManager.class); - - private static final String ELEMENT_DASHBOARD = "dashboard"; - private static final String ELEMENT_PAGE = "page"; - private static final String ELEMENT_COLUMN = "column"; - private static final String ELEMENT_DASHLET = "dashlet"; - private static final String ATTR_ID = "id"; - private static final String ATTR_LAYOUTID = "layout-id"; - private static final String ATTR_REFID = "idref"; - - private List pages = new ArrayList(4); - private Page currentPage = null; - - - /** - * Default constructor - */ - public PageConfig() - { - } - - /** - * Copy constructor - * - * @param copy PageConfig to copy - */ - public PageConfig(PageConfig copy) - { - this.pages = new ArrayList(copy.pages.size()); - for (Page page : copy.pages) - { - // invoke the copy constructor on each Page - // which in turn calls the copy constructor of child classes - this.pages.add(new Page(page)); - } - } - - /** - * @return The current page in the config - */ - public Page getCurrentPage() - { - if (this.currentPage == null) - { - if (this.pages.size() != 0) - { - this.currentPage = pages.get(0); - } - } - return this.currentPage; - } - - /** - * Set the current Page for the cnfig - * - * @param pageId ID of the page to set as current - */ - public void setCurrentPage(String pageId) - { - for (Page page : pages) - { - if (page.getId().equals(pageId)) - { - this.currentPage = page; - break; - } - } - } - - /** - * Add a new Page to the list - * - * @param page Page to add - */ - public void addPage(Page page) - { - pages.add(page); - } - - /** - * Get a Page with the specified page Id - * - * @param pageId Of the page to return - * - * @return Page or null if not found - */ - public Page getPage(String pageId) - { - Page foundPage = null; - for (Page page : pages) - { - if (page.getId().equals(pageId)) - { - foundPage = page; - break; - } - } - return foundPage; - } - - /** - * Convert this config to an XML definition which can be serialized. - * Example: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * @return XML for this config - */ - public String toXML() - { - try - { - Document doc = DocumentHelper.createDocument(); - - Element root = doc.addElement(ELEMENT_DASHBOARD); - for (Page page : pages) - { - Element pageElement = root.addElement(ELEMENT_PAGE); - pageElement.addAttribute(ATTR_ID, page.getId()); - pageElement.addAttribute(ATTR_LAYOUTID, page.getLayoutDefinition().Id); - for (Column column : page.getColumns()) - { - Element columnElement = pageElement.addElement(ELEMENT_COLUMN); - for (DashletDefinition dashletDef : column.getDashlets()) - { - columnElement.addElement(ELEMENT_DASHLET).addAttribute(ATTR_REFID, dashletDef.Id); - } - } - } - - StringWriter out = new StringWriter(512); - XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint()); - writer.setWriter(out); - writer.write(doc); - - return out.toString(); - } - catch (Throwable err) - { - throw new AlfrescoRuntimeException("Unable to serialize Dashboard PageConfig to XML: " + err.getMessage(), err); - } - } - - @Override - public String toString() - { - return toXML(); - } - - /** - * Deserialise this PageConfig instance from the specified XML stream. - * - * @param xml - */ - public void fromXML(DashboardsConfigElement config, String xml) - { - try - { - SAXReader reader = new SAXReader(); - Document document = reader.read(new StringReader(xml)); - Element rootElement = document.getRootElement(); - - // walk the pages found in xml - Iterator itrPages = rootElement.elementIterator(ELEMENT_PAGE); - while (itrPages.hasNext()) - { - Element pageElement = (Element)itrPages.next(); - String layoutId = pageElement.attributeValue(ATTR_LAYOUTID); - LayoutDefinition layoutDef = config.getLayoutDefinition(layoutId); - if (layoutDef != null) - { - // found the layout now build the page and read the columns - Page page = new Page(pageElement.attributeValue(ATTR_ID), layoutDef); - Iterator itrColumns = pageElement.elementIterator(ELEMENT_COLUMN); - while (itrColumns.hasNext()) - { - Column column = new Column(); - - // read and resolve the dashlet definitions for this column - Element columnElement = (Element)itrColumns.next(); - Iterator itrDashlets = columnElement.elementIterator(ELEMENT_DASHLET); - while (itrDashlets.hasNext()) - { - String dashletId = ((Element)itrDashlets.next()).attributeValue(ATTR_REFID); - DashletDefinition dashletDef = config.getDashletDefinition(dashletId); - if (dashletDef != null) - { - column.addDashlet(dashletDef); - } - else if (logger.isWarnEnabled()) - { - logger.warn("Failed to resolve Dashboard Dashlet Definition ID: " + dashletId); - } - } - - // add the column of dashlets to the page - page.addColumn(column); - } - - // add the page to this config instance - this.addPage(page); - } - else if (logger.isWarnEnabled()) - { - logger.warn("Failed to resolve Dashboard Layout Definition ID: " + layoutId); - } - } - } - catch (DocumentException docErr) - { - // if we cannot parse, then we simply revert to default - } - } -} - -/** - * Simple class to represent a Page in a Dashboard. - * Each Page has a Layout associated with it, and a number of Column definitions. - */ -final class Page implements Serializable -{ - private static final long serialVersionUID = 8023042580316126423L; - - private String id; - private LayoutDefinition layoutDef; - private List columns = new ArrayList(4); - - /** - * Constructor - * - * @param id - * @param layout - */ - public Page(String id, LayoutDefinition layout) - { - if (id == null || id.length() == 0) - { - throw new IllegalArgumentException("ID for a Dashboard Page is mandatory."); - } - if (layout == null) - { - throw new IllegalArgumentException("Layout for a Dashboard Page is mandatory."); - } - this.id = id; - this.layoutDef = layout; - } - - /** - * Copy Constructor - * - * @param copy Page to build a copy from - */ - public Page(Page copy) - { - this.id = copy.id; - this.layoutDef = copy.layoutDef; - for (Column column : copy.columns) - { - Column cloneColumn = new Column(column); - addColumn(cloneColumn); - } - } - - public String getId() - { - return this.id; - } - - public LayoutDefinition getLayoutDefinition() - { - return this.layoutDef; - } - - public void setLayoutDefinition(LayoutDefinition layout) - { - if (layout == null) - { - throw new IllegalArgumentException("Layout for a Dashboard Page is mandatory."); - } - - // correct column collection based on new layout definition - while (this.columns.size() < layout.Columns) - { - addColumn(new Column()); - } - if (this.columns.size() > layout.Columns) - { - this.columns = this.columns.subList(0, layout.Columns); - } - - this.layoutDef = layout; - } - - public void addColumn(Column column) - { - this.columns.add(column); - } - - public List getColumns() - { - return this.columns; - } -} - -/** - * Simple class representing a single Column in a dashboard Page. - * Each column contains a list of Dashlet definitions. - */ -final class Column implements Serializable -{ - private static final long serialVersionUID = 6462844390234508010L; - - private List dashlets = new ArrayList(4); - - /** - * Default constructor - */ - public Column() - { - } - - /** - * Copy constructor - * - * @param copy Column to copy - */ - public Column(Column copy) - { - this.dashlets = new ArrayList(copy.dashlets.size()); - this.dashlets.addAll(copy.dashlets); - } - - public void addDashlet(DashletDefinition dashlet) - { - dashlets.add(dashlet); - } - - public List getDashlets() - { - return this.dashlets; - } - - public void trimDashlets(int max) - { - if (max >= 0) - { - int maxTrim = Math.min(this.dashlets.size(), max); - this.dashlets = this.dashlets.subList(0, maxTrim); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/dialog/BaseDialogBean.java b/war/src/main/java/org/alfresco/web/bean/dialog/BaseDialogBean.java deleted file mode 100644 index 25447b090c..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/dialog/BaseDialogBean.java +++ /dev/null @@ -1,457 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.dialog; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.repo.transaction.RetryingTransactionHelper; -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.service.cmr.coci.CheckOutCheckInService; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.model.FileFolderService; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.rule.RuleService; -import org.alfresco.service.cmr.search.SearchService; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.transaction.TransactionService; -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.bean.BrowseBean; -import org.alfresco.web.bean.NavigationBean; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.config.DialogsConfigElement.DialogButtonConfig; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; - -/** - * Base class for all dialog beans providing common functionality - * - * @author gavinc - */ -@SuppressWarnings("serial") -public abstract class BaseDialogBean implements IDialogBean, Serializable -{ - protected Map parameters; - protected boolean isFinished = false; - - // services common to most dialogs - protected BrowseBean browseBean; - protected NavigationBean navigator; - - transient private TransactionService transactionService; - transient private NodeService nodeService; - transient private CheckOutCheckInService checkOutCheckInService; - transient private FileFolderService fileFolderService; - transient private SearchService searchService; - transient private DictionaryService dictionaryService; - transient private NamespaceService namespaceService; - transient private RuleService ruleService; - - public void init(Map parameters) - { - // tell any beans to update themselves so the UI gets refreshed - UIContextService.getInstance(FacesContext.getCurrentInstance()).notifyBeans(); - - // store the parameters, create empty map if necessary - this.parameters = parameters; - - if (this.parameters == null) - { - this.parameters = Collections.emptyMap(); - } - - // reset the isFinished flag - this.isFinished = false; - } - - public void restored() - { - // do nothing by default, subclasses can override if necessary - } - - public String cancel() - { - // remove container variable - FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove( - AlfrescoNavigationHandler.EXTERNAL_CONTAINER_SESSION); - - return getDefaultCancelOutcome(); - } - - public String finish() - { - final FacesContext context = FacesContext.getCurrentInstance(); - final String defaultOutcome = getDefaultFinishOutcome(); - String outcome = null; - - // check the isFinished flag to stop the finish button - // being pressed multiple times - if (this.isFinished == false) - { - this.isFinished = true; - - RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(context); - RetryingTransactionCallback callback = new RetryingTransactionCallback() - { - public String execute() throws Throwable - { - // call the actual implementation - return finishImpl(context, defaultOutcome); - } - }; - try - { - // Execute - outcome = txnHelper.doInTransaction(callback, false, true); - - // allow any subclasses to perform post commit processing - // i.e. resetting state or setting status messages - outcome = doPostCommitProcessing(context, outcome); - - // remove container variable - context.getExternalContext().getSessionMap().remove( - AlfrescoNavigationHandler.EXTERNAL_CONTAINER_SESSION); - } - catch (Throwable e) - { - // reset the flag so we can re-attempt the operation - isFinished = false; - outcome = getErrorOutcome(e); - if (e instanceof ReportedException == false) - { - Utils.addErrorMessage(formatErrorMessage(e), e); - } - ReportedException.throwIfNecessary(e); - } - } - else - { - Utils.addErrorMessage(Application.getMessage(context, "error_wizard_completed_already")); - } - - return outcome; - } - - public boolean isFinished() - { - return isFinished; - } - - public List getAdditionalButtons() - { - // none by default, subclasses can override if necessary - - return null; - } - - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "cancel"); - } - - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "ok"); - } - - public boolean getFinishButtonDisabled() - { - return true; - } - - public String getContainerTitle() - { - // nothing by default, subclasses can override if necessary - - return null; - } - - public String getContainerSubTitle() - { - // nothing by default, subclasses can override if necessary - - return null; - } - - public String getContainerDescription() - { - // nothing by default, subclasses can override if necessary - - return null; - } - - public Object getActionsContext() - { - // return the current node as the context for actions be default - // dialog implementations can override this method to return the - // appropriate object for their use case - - if (this.navigator == null) - { - throw new AlfrescoRuntimeException("To use actions in the dialog the 'navigator' " + - "property must be injected with an instance of NavigationBean!"); - } - - return this.navigator.getCurrentNode(); - } - - public String getActionsConfigId() - { - // nothing by default, subclasses can override if necessary - - return null; - } - - public String getMoreActionsConfigId() - { - // nothing by default, subclasses can override if necessary - - return null; - } - - /** - * @param browseBean The BrowseBean to set. - */ - public void setBrowseBean(BrowseBean browseBean) - { - this.browseBean = browseBean; - } - - /** - * @param navigator The NavigationBean to set. - */ - public void setNavigator(NavigationBean navigator) - { - this.navigator = navigator; - } - - protected TransactionService getTransactionService() - { - if (this.transactionService == null) - { - this.transactionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getTransactionService(); - } - return this.transactionService; - } - - /** - * @param nodeService The nodeService to set. - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - protected NodeService getNodeService() - { - if (this.nodeService == null) - { - this.nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - } - return this.nodeService; - } - - protected CheckOutCheckInService getCheckOutCheckInService() - { - if (this.checkOutCheckInService == null) - { - this.checkOutCheckInService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getCheckOutCheckInService(); - } - return this.checkOutCheckInService; - } - - /** - * Get the rule service - * @return RuleService rule service - */ - protected RuleService getRuleService() - { - if (ruleService == null) - { - ruleService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getRuleService(); - } - return ruleService; - } - - /** - * @param fileFolderService used to manipulate folder/folder model nodes - */ - public void setFileFolderService(FileFolderService fileFolderService) - { - this.fileFolderService = fileFolderService; - } - - protected FileFolderService getFileFolderService() - { - if (this.fileFolderService == null) - { - this.fileFolderService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getFileFolderService(); - } - return this.fileFolderService; - } - - /** - * @param searchService the service used to find nodes - */ - public void setSearchService(SearchService searchService) - { - this.searchService = searchService; - } - - protected SearchService getSearchService() - { - if (this.searchService == null) - { - this.searchService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getSearchService(); - } - return this.searchService; - } - - /** - * Sets the dictionary service - * - * @param dictionaryService the dictionary service - */ - public void setDictionaryService(DictionaryService dictionaryService) - { - this.dictionaryService = dictionaryService; - } - - protected DictionaryService getDictionaryService() - { - if (this.dictionaryService == null) - { - this.dictionaryService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getDictionaryService(); - } - return this.dictionaryService; - } - - /** - * @param namespaceService The NamespaceService - */ - public void setNamespaceService(NamespaceService namespaceService) - { - this.namespaceService = namespaceService; - } - - protected NamespaceService getNamespaceService() - { - if (this.namespaceService == null) - { - this.namespaceService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNamespaceService(); - } - return this.namespaceService; - } - - /** - * Returns the default cancel outcome - * - * @return Default close outcome, dialog:close by default - */ - protected String getDefaultCancelOutcome() - { - return AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME; - } - - /** - * Returns the default finish outcome - * - * @return Default finish outcome, dialog:close by default - */ - protected String getDefaultFinishOutcome() - { - return AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME; - } - - /** - * Performs the actual processing for the wizard. - * NOTE: This method is called within the context of a transaction - * so no transaction handling is required - * - * @param context FacesContext - * @param outcome The default outcome - * @return The outcome - */ - protected abstract String finishImpl(FacesContext context, String outcome) - throws Throwable; - - /** - * Performs any post commit processing subclasses may want to provide - * - * @param context FacesContext - * @param outcome The default outcome - * @return The outcome - */ - protected String doPostCommitProcessing(FacesContext context, String outcome) - { - // do nothing by default, subclasses can override if necessary - - return outcome; - } - - /** - * The default message id to use in error messages - * - * @return The error message lookup id - */ - protected String getErrorMessageId() - { - return Repository.ERROR_GENERIC; - } - - /** - * The outcome to return if the given exception occurs - * - * @param exception The exception that got thrown - * @return The error outcome, null by default - */ - protected String getErrorOutcome(Throwable exception) - { - return null; - } - - /** - * Returns a formatted exception string for the given exception - * - * @param exception The exception that got thrown - * @return The formatted message - */ - protected String formatErrorMessage(Throwable exception) - { - return MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), getErrorMessageId()), - exception.getMessage()); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/dialog/ChangeViewSupport.java b/war/src/main/java/org/alfresco/web/bean/dialog/ChangeViewSupport.java deleted file mode 100644 index a99f431722..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/dialog/ChangeViewSupport.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.dialog; - -import java.util.List; -import javax.faces.event.ActionEvent; -import org.alfresco.web.ui.common.component.UIListItem; - -/** - * Interface definition for dialog beans that wish to use the view - * drop down to change the layout of the dialog. - * - * @author gavinc - */ -public interface ChangeViewSupport -{ - public List getViewItems(); - - public String getViewMode(); - - public void setViewMode(String viewMode); - - public void viewModeChanged(ActionEvent event); -} diff --git a/war/src/main/java/org/alfresco/web/bean/dialog/DialogManager.java b/war/src/main/java/org/alfresco/web/bean/dialog/DialogManager.java deleted file mode 100644 index dd6f2a7d4c..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/dialog/DialogManager.java +++ /dev/null @@ -1,547 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.dialog; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.config.DialogsConfigElement.DialogButtonConfig; -import org.alfresco.web.config.DialogsConfigElement.DialogConfig; -import org.alfresco.web.ui.common.component.UIActionLink; - -/** - * Bean that manages the dialog framework - * - * @author gavinc - */ -public final class DialogManager implements Serializable -{ - private static final long serialVersionUID = -8690844273074627353L; - - public final static String BEAN_NAME = "DialogManager"; - - private DialogState currentDialogState; - private Map paramsToApply; - - /** - * Sets the parameters the next dialog will initialise with - * - * @param params The parameters - */ - public void setupParameters(Map params) - { - this.paramsToApply = params; - } - - /** - * Action handler used to setup parameters for the dialog being launched - * - * @param event The event containing the parameters - */ - public void setupParameters(ActionEvent event) - { - // check the component the event come from was an action link - UIComponent component = event.getComponent(); - if (component instanceof UIActionLink) - { - // store the parameters - this.paramsToApply = ((UIActionLink)component).getParameterMap(); - - // make sure "null" parameters are actually null, this can occur - // when null parameters are sent to the client and posted back - for (String name : this.paramsToApply.keySet()) - { - String value = this.paramsToApply.get(name); - if (value != null && value.equalsIgnoreCase("null")) - { - this.paramsToApply.put(name, null); - } - } - } - } - - /** - * Sets the current dialog - * - * @param config The configuration for the dialog to set - */ - public void setCurrentDialog(DialogConfig config) - { - // make sure the managed bean is present - String beanName = config.getManagedBean(); - - Object bean = FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), beanName); - - if (bean == null) - { - throw new AlfrescoRuntimeException("Failed to start dialog as managed bean '" + beanName + - "' has not been defined"); - } - - // make sure the bean implements the IDialogBean interface - IDialogBean dialog = null; - if (bean instanceof IDialogBean) - { - dialog = (IDialogBean)bean; - } - else - { - throw new AlfrescoRuntimeException("Failed to start dialog as managed bean '" + beanName + - "' does not implement the required IDialogBean interface"); - } - - // create the DialogState object - this.currentDialogState = new DialogState(config, dialog); - - // initialise the managed bean - dialog.init(this.paramsToApply); - - // reset the current parameters so subsequent dialogs don't get them - this.paramsToApply = null; - } - - /** - * Returns the state of the currently active dialog - * - * @return Current dialog's state - */ - public DialogState getState() - { - return this.currentDialogState; - } - - /** - * Restores the dialog represented by the given DialogState object. - * NOTE: The dialog's restored() method is also called during this - * method. - * - * @param state The DialogState for the dialog to restore - */ - public void restoreState(DialogState state) - { - this.currentDialogState = state; - - // retrieve the dialog and call it's restored() method - this.currentDialogState.getDialog().restored(); - } - - /** - * Returns the config for the current dialog - * - * @return The current dialog config - */ - public DialogConfig getCurrentDialog() - { - return this.currentDialogState.getConfig(); - } - - /** - * Returns the current dialog bean being managed - * - * @return The current managed bean - */ - public IDialogBean getBean() - { - return this.currentDialogState.getDialog(); - } - - /** - * Returns the icon to use for the current dialog - * - * @return The icon - */ - public String getIcon() - { - return this.currentDialogState.getConfig().getIcon(); - } - - /** - * Returns the error message to use in error conditions - * - * @return The error message - */ - public String getErrorMessage() - { - return Application.getMessage(FacesContext.getCurrentInstance(), - this.currentDialogState.getConfig().getErrorMessageId()); - } - - /** - * Returns the resolved title to use for the dialog - * - * @return The title - */ - public String getTitle() - { - // try and get the title directly from the dialog - String title = this.currentDialogState.getDialog().getContainerTitle(); - - if (title == null) - { - // try and get the title via a message bundle key - title = this.currentDialogState.getConfig().getTitleId(); - - if (title != null) - { - title = Application.getMessage(FacesContext.getCurrentInstance(), title); - } - else - { - // try and get the title from the configuration - title = this.currentDialogState.getConfig().getTitle(); - } - } - - return title; - } - - /** - * Returns the resolved subtitle to use for the dialog - * - * @return The subtitle - */ - public String getSubTitle() - { - // try and get the subtitle directly from the dialog - String subTitle = this.currentDialogState.getDialog().getContainerSubTitle(); - - if (subTitle == null) - { - // try and get the title via a message bundle key - subTitle = this.currentDialogState.getConfig().getSubTitleId(); - - if (subTitle != null) - { - subTitle = Application.getMessage(FacesContext.getCurrentInstance(), subTitle); - } - else - { - // try and get the title from the configuration - subTitle = this.currentDialogState.getConfig().getSubTitle(); - } - } - - return subTitle; - } - - /** - * Returns the resolved description to use for the dialog - * - * @return The description - */ - public String getDescription() - { - // try and get the description directly from the dialog - String desc = this.currentDialogState.getDialog().getContainerDescription(); - - if (desc == null) - { - // try and get the description via a message bundle key - desc = this.currentDialogState.getConfig().getDescriptionId(); - - if (desc != null) - { - desc = Application.getMessage(FacesContext.getCurrentInstance(), desc); - } - else - { - // try and get the description from the configuration - desc = this.currentDialogState.getConfig().getDescription(); - } - } - - return desc; - } - - /** - * Returns the page the dialog will use - * - * @return The page - */ - public String getPage() - { - return this.currentDialogState.getConfig().getPage(); - } - - /** - * Returns the id of a configured action group representing the actions to - * display for the dialog - * - * @return The action group id - */ - public String getActionsId() - { - // first see if the dialog itself has supplied an actions id - String configId = this.currentDialogState.getDialog().getActionsConfigId(); - - if (configId == null) - { - // see if an actions id was specified in the dialog config - configId = this.currentDialogState.getConfig().getActionsConfigId(); - } - - return configId; - } - - /** - * Returns the id of a configured action group representing the - * 'more actions' to display for the dialog - * - * @return The action group id - */ - public String getMoreActionsId() - { - // first see if the dialog itself has supplied a more actions id - String configId = this.currentDialogState.getDialog().getMoreActionsConfigId(); - - if (configId == null) - { - // see if an actions id was specified in the dialog config - configId = this.currentDialogState.getConfig().getMoreActionsConfigId(); - } - - return configId; - } - - /** - * Returns the object to use as the context for the main and more - * actions that may be configured by the dialog - * - * @return Object to use as the context for actions, the current - * node by default - */ - public Object getActionsContext() - { - return this.currentDialogState.getDialog().getActionsContext(); - } - - /** - * Returns the label to use for the main actions when a menu is being used - * - * @return The actions menu label - */ - public String getActionsMenuLabel() - { - // try and get the label via a message bundle key - String label = this.currentDialogState.getConfig().getActionsMenuLabelId(); - - if (label != null) - { - label = Application.getMessage(FacesContext.getCurrentInstance(), label); - } - else - { - // try and get the description from the configuration - label = this.currentDialogState.getConfig().getActionsMenuLabel(); - } - - // if the label is still null use the default of 'Create' - if (label == null) - { - label = Application.getMessage(FacesContext.getCurrentInstance(), "create_options"); - } - - return label; - } - - /** - * Returns the label to use for the more actions menu - * - * @return The more actions menu label - */ - public String getMoreActionsMenuLabel() - { - // try and get the label via a message bundle key - String label = this.currentDialogState.getConfig().getMoreActionsMenuLabelId(); - - if (label != null) - { - label = Application.getMessage(FacesContext.getCurrentInstance(), label); - } - else - { - // try and get the description from the configuration - label = this.currentDialogState.getConfig().getMoreActionsMenuLabel(); - } - - // if the label is still null use the default of 'More Actions' - if (label == null) - { - label = Application.getMessage(FacesContext.getCurrentInstance(), "more_actions"); - } - - return label; - } - - /** - * Determines whether the main actions should be rendered as a - * menu - * - * @return true to render the main set of actions as a menu, false - * to render them as a horizontal list - */ - public boolean getActionsAsMenu() - { - return this.currentDialogState.getConfig().getActionsAsMenu(); - } - - /** - * Determines whether the current dialog's OK button is visible - * - * @return true if the OK button is visible, false if it's not - */ - public boolean isOKButtonVisible() - { - return this.currentDialogState.getConfig().isOKButtonVisible(); - } - - /** - * Determines whether the current dialog should display the next - * and previous buttons in the header area - * - * @return true if navigation support is enabled - */ - public boolean isNavigationVisible() - { - return (getBean() instanceof NavigationSupport); - } - - /** - * Determines whether the current dialog should display the list - * of views in the header area - * - * @return true if change view support is enabled - */ - public boolean isViewListVisible() - { - return (getBean() instanceof ChangeViewSupport); - } - - /** - * Determines whether the current dialog should display the list - * of filters in the header area - * - * @return true if filter support is enabled - */ - public boolean isFilterListVisible() - { - return (getBean() instanceof FilterViewSupport); - } - - /** - * Returns a list of additional buttons to display in the dialog - * - * @return List of button configurations - */ - public List getAdditionalButtons() - { - List buttons = null; - - // get a list of buttons to display from the configuration - List cfgButtons = this.currentDialogState.getConfig().getButtons(); - - // get a list of buttons added dynamically by the dialog - List dynButtons = this.currentDialogState.getDialog().getAdditionalButtons(); - - if (cfgButtons != null && dynButtons != null) - { - // combine the two lists - buttons = new ArrayList( - cfgButtons.size() + dynButtons.size()); - buttons.addAll(cfgButtons); - buttons.addAll(dynButtons); - } - else if (cfgButtons != null && dynButtons == null) - { - buttons = cfgButtons; - } - else if (cfgButtons == null && dynButtons != null) - { - buttons = dynButtons; - } - - return buttons; - } - - /** - * Returns the label to use for the cancel button - * - * @return The cancel button label - */ - public String getCancelButtonLabel() - { - return this.currentDialogState.getDialog().getCancelButtonLabel(); - } - - /** - * Returns the label to use for the finish button - * - * @return The finish button label - */ - public String getFinishButtonLabel() - { - return this.currentDialogState.getDialog().getFinishButtonLabel(); - } - - /** - * Determines whether the finish button on the dialog should be disabled - * - * @return true if the button should be disabled - */ - public boolean getFinishButtonDisabled() - { - return this.currentDialogState.getDialog().getFinishButtonDisabled(); - } - - /** - * Method handler called when the finish button of the dialog is pressed - * - * @return The outcome - */ - public String finish() - { - return this.currentDialogState.getDialog().finish(); - } - - /** - * Method handler called when the cancel button of the dialog is pressed - * - * @return The outcome - */ - public String cancel() - { - return this.currentDialogState.getDialog().cancel(); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/dialog/DialogState.java b/war/src/main/java/org/alfresco/web/bean/dialog/DialogState.java deleted file mode 100644 index f8d0e5c5ca..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/dialog/DialogState.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.dialog; - -import java.io.Serializable; - -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.config.DialogsConfigElement.DialogConfig; - -/** - * Object responsible for holding the current state of an active dialog. - * - * @author gavinc - */ -public final class DialogState implements Serializable -{ - private static final long serialVersionUID = -5007635589636930602L; - - private DialogConfig config; - private IDialogBean dialog; - - /** - * Default constructor - * - * @param config The configuration for the dialog - * @param dialog The dialog bean instance - */ - public DialogState(DialogConfig config, IDialogBean dialog) - { - this.config = config; - this.dialog = dialog; - } - - /** - * Returns the configuration for the dialog - * - * @return The dialog configuration - */ - public DialogConfig getConfig() - { - return config; - } - - /** - * Returns the bean representing the dialog instance - * - * @return The dialog bean instance - */ - public IDialogBean getDialog() - { - return dialog; - } - - @Override - public String toString() - { - return AlfrescoNavigationHandler.DIALOG_PREFIX + this.config.getName(); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/dialog/FilterViewSupport.java b/war/src/main/java/org/alfresco/web/bean/dialog/FilterViewSupport.java deleted file mode 100644 index 90886b1de5..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/dialog/FilterViewSupport.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.dialog; - -import java.util.List; -import javax.faces.event.ActionEvent; -import org.alfresco.web.ui.common.component.UIListItem; - -/** - * Interface definition for dialog beans that wish to use the filter - * drop down to change the contents of the dialog. - * - * @author gavinc - */ -public interface FilterViewSupport -{ - public List getFilterItems(); - - public String getFilterMode(); - - public void setFilterMode(String filterMode); - - public void filterModeChanged(ActionEvent event); -} diff --git a/war/src/main/java/org/alfresco/web/bean/dialog/IDialogBean.java b/war/src/main/java/org/alfresco/web/bean/dialog/IDialogBean.java deleted file mode 100644 index 5c0a0a5e47..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/dialog/IDialogBean.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.dialog; - -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -import org.alfresco.web.config.DialogsConfigElement.DialogButtonConfig; - -/** - * Interface that defines the contract for a dialog backing bean - * - * @author gavinc - */ -public interface IDialogBean extends Serializable -{ - /** - * Initialises the dialog bean - * - * @param parameters Map of parameters for the dialog - */ - public void init(Map parameters); - - /** - * Called when the dialog is restored after a nested dialog is closed - */ - public void restored(); - - /** - * Method handler called when the cancel button of the dialog is pressed - * - * @return The outcome to return - */ - public String cancel(); - - /** - * Method handler called when the finish button of the dialog is pressed - * - * @return The outcome to return - */ - public String finish(); - - /** - * Returns a list of additional buttons to display in the dialog. - * - * @return List of button configurations, null if there are no buttons - */ - public List getAdditionalButtons(); - - /** - * Returns the label to use for the cancel button - * - * @return The cancel button label - */ - public String getCancelButtonLabel(); - - /** - * Returns the label to use for the finish button - * - * @return The finish button label - */ - public String getFinishButtonLabel(); - - /** - * Determines whether the finish button on the dialog should be disabled - * - * @return true if the button should be disabled - */ - public boolean getFinishButtonDisabled(); - - /** - * Returns the title to be used for the dialog - *

If this returns null the DialogManager will - * lookup the title via the dialog configuration

- * - * @return The title or null if the title is to be acquired via configuration - */ - public String getContainerTitle(); - - /** - * Returns the subtitle to be used for the dialog - *

If this returns null the DialogManager will - * lookup the subtitle via the dialog configuration

- * - * @return The subtitle or null if the subtitle is to be acquired via configuration - */ - public String getContainerSubTitle(); - - /** - * Returns the description to be used for the dialog - *

If this returns null the DialogManager will - * lookup the description via the dialog configuration

- * - * @return The title or null if the title is to be acquired via configuration - */ - public String getContainerDescription(); - - /** - * Returns the object to use as the context for the main and more - * actions that may be configured by the dialog - * - * @return Object to use as the context for actions - */ - public Object getActionsContext(); - - /** - * Returns the id of an action group to use for the main actions - * - * @return Id of an action group - */ - public String getActionsConfigId(); - - /** - * Returns the id of an action group to use for the more actions - * - * @return Id of an action group - */ - public String getMoreActionsConfigId(); - - /** - * Determines whether the has finished - * - * @return true if the wizard has finished - */ - public boolean isFinished(); -} diff --git a/war/src/main/java/org/alfresco/web/bean/dialog/NavigationSupport.java b/war/src/main/java/org/alfresco/web/bean/dialog/NavigationSupport.java deleted file mode 100644 index 25454b79c5..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/dialog/NavigationSupport.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.dialog; - -import javax.faces.event.ActionEvent; - -/** - * Interface definition for dialog beans that wish to use the next - * previous buttons for quick navigation. - * - * @author gavinc - */ -public interface NavigationSupport -{ - public String getCurrentItemId(); - - public void nextItem(ActionEvent event); - - public void previousItem(ActionEvent event); - - public String getOutcome(); -} diff --git a/war/src/main/java/org/alfresco/web/bean/forums/CreateDiscussionDialog.java b/war/src/main/java/org/alfresco/web/bean/forums/CreateDiscussionDialog.java deleted file mode 100644 index 8e5f7e5cba..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/forums/CreateDiscussionDialog.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.forums; - -import java.text.MessageFormat; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.AbortProcessingException; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.model.ForumModel; -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.RegexQNamePattern; -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean implementation for the "Create Discusssion Dialog". - * - * @author gavinc - */ -public class CreateDiscussionDialog extends CreateTopicDialog -{ - private static final long serialVersionUID = 3500493916528264014L; - - protected NodeRef discussingNodeRef; - - private static final Log logger = LogFactory.getLog(CreateDiscussionDialog.class); - - // ------------------------------------------------------------------------------ - // Wizard implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - // get the id of the node we are creating the discussion for - String id = parameters.get("id"); - if (id == null || id.length() == 0) - { - throw new AlfrescoRuntimeException("createDiscussion called without an id"); - } - - // create the topic to hold the discussions - createTopic(id); - } - - @Override - public String cancel() - { - // if the user cancels the creation of a discussion all the setup that was done - // when the dialog started needs to be undone i.e. removing the created forum - // and the discussable aspect - deleteTopic(); - - // as we are cancelling the creation of a discussion we know we need to go back - // to the browse screen, this also makes sure we don't end up in the forum that - // just got deleted! - FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove( - AlfrescoNavigationHandler.EXTERNAL_CONTAINER_SESSION); - return getDefaultCancelOutcome(); - } - - // ------------------------------------------------------------------------------ - // Helper methods - - /** - * Creates a topic for the node with the given id - * - * @param id The id of the node to discuss - */ - protected void createTopic(final String id) - { - RetryingTransactionCallback createTopicCallback = new RetryingTransactionCallback() - { - public NodeRef execute() throws Throwable - { - NodeRef forumNodeRef = null; - discussingNodeRef = new NodeRef(Repository.getStoreRef(), id); - - if (getNodeService().hasAspect(discussingNodeRef, ForumModel.ASPECT_DISCUSSABLE)) - { - throw new AlfrescoRuntimeException("createDiscussion called for an object that already has a discussion!"); - } - - // Add the discussable aspect - getNodeService().addAspect(discussingNodeRef, ForumModel.ASPECT_DISCUSSABLE, null); - // The discussion aspect create the necessary child - List destChildren = getNodeService().getChildAssocs( - discussingNodeRef, - ForumModel.ASSOC_DISCUSSION, - RegexQNamePattern.MATCH_ALL); - // Take the first one - if (destChildren.size() == 0) - { - // Drop the aspect and recreate it. This should not happen, but just in case ... - getNodeService().removeAspect(discussingNodeRef, ForumModel.ASPECT_DISCUSSABLE); - getNodeService().addAspect(discussingNodeRef, ForumModel.ASPECT_DISCUSSABLE, null); - // The discussion aspect create the necessary child - destChildren = getNodeService().getChildAssocs( - discussingNodeRef, - ForumModel.ASSOC_DISCUSSION, - RegexQNamePattern.MATCH_ALL); - } - if (destChildren.size() == 0) - { - throw new AlfrescoRuntimeException("The discussable aspect behaviour is not creating a topic"); - } - else - { - // We just take the first one - ChildAssociationRef discussionAssoc = destChildren.get(0); - forumNodeRef = discussionAssoc.getChildRef(); - } - - if (logger.isDebugEnabled()) - logger.debug("created forum for content: " + discussingNodeRef.toString()); - - return forumNodeRef; - } - }; - - FacesContext context = FacesContext.getCurrentInstance(); - NodeRef forumNodeRef = null; - try - { - forumNodeRef = getTransactionService().getRetryingTransactionHelper().doInTransaction( - createTopicCallback, false); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {id}) ); - throw new AbortProcessingException("Invalid node reference"); - } - catch (Throwable e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - context, Repository.ERROR_GENERIC), e.getMessage()), e); - ReportedException.throwIfNecessary(e); - } - // finally setup the context for the forum we just created - if (forumNodeRef != null) - { - this.browseBean.clickSpace(forumNodeRef); - } - } - - /** - * Deletes the setup performed during the initialisation of the dialog. - */ - protected void deleteTopic() - { - RetryingTransactionCallback deleteTopicCallback = new RetryingTransactionCallback() - { - public Object execute() throws Throwable - { - // remove this node from the breadcrumb if required - Node forumNode = navigator.getCurrentNode(); - browseBean.removeSpaceFromBreadcrumb(forumNode); - - // remove the discussable aspect from the node we were going to discuss! - // AWC-1519: removing the aspect that defines the child association now does the - // cascade delete so we no longer have to delete the child explicitly - getNodeService().removeAspect(discussingNodeRef, ForumModel.ASPECT_DISCUSSABLE); - // Done - return null; - } - }; - FacesContext context = FacesContext.getCurrentInstance(); - try - { - getTransactionService().getRetryingTransactionHelper().doInTransaction(deleteTopicCallback, false); - } - catch (Throwable e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - context, Repository.ERROR_GENERIC), e.getMessage()), e); - ReportedException.throwIfNecessary(e); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/forums/CreateForumDialog.java b/war/src/main/java/org/alfresco/web/bean/forums/CreateForumDialog.java deleted file mode 100644 index fc744f154c..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/forums/CreateForumDialog.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.forums; - -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ForumModel; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.spaces.CreateSpaceDialog; - -/** - * Bean used to implement the "Create Forum Dialog". - * - * @author gavinc - */ -public class CreateForumDialog extends CreateSpaceDialog -{ - // ------------------------------------------------------------------------------ - // Wizard implementation - - private static final long serialVersionUID = 277281993463789379L; - - @Override - public void init(Map parameters) - { - super.init(parameters); - - this.spaceType = ForumModel.TYPE_FORUM.toString(); - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "create_forum"); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/forums/CreateForumsDialog.java b/war/src/main/java/org/alfresco/web/bean/forums/CreateForumsDialog.java deleted file mode 100644 index a1394cb04a..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/forums/CreateForumsDialog.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.forums; - -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ForumModel; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.spaces.CreateSpaceDialog; - -/** - * Bean used to implement the "Create Forums Dialog". - * - * @author gavinc - */ -public class CreateForumsDialog extends CreateSpaceDialog -{ - // ------------------------------------------------------------------------------ - // Wizard implementation - - private static final long serialVersionUID = 4371868975654509241L; - - @Override - public void init(Map parameters) - { - super.init(parameters); - - this.spaceType = ForumModel.TYPE_FORUMS.toString(); - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "create_forums"); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/forums/CreatePostDialog.java b/war/src/main/java/org/alfresco/web/bean/forums/CreatePostDialog.java deleted file mode 100644 index d31e34484c..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/forums/CreatePostDialog.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.forums; - -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ForumModel; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.content.CreateContentWizard; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.Utils; - -/** - * Bean implementation of the "New Post Dialog". - * - * @author gavinc - */ -public class CreatePostDialog extends CreateContentWizard -{ - // ------------------------------------------------------------------------------ - // Wizard implementation - - private static final long serialVersionUID = -2859329677883776068L; - - @Override - public void init(Map parameters) - { - super.init(parameters); - - // set up for creating a post - this.objectType = ForumModel.TYPE_POST.toString(); - - // make sure we don't show the edit properties dialog after creation - this.showOtherProperties = false; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - // create appropriate values for filename and content type - this.fileName = ForumsBean.createPostFileName(); - this.mimeType = Repository.getMimeTypeForFileName( - FacesContext.getCurrentInstance(), this.fileName); - - // remove link breaks and replace with
- this.content = Utils.replaceLineBreaks(this.content, false); - - // set UTF-8 encoding for the post (all original posts are UTF-8 also) - this.encoding = "UTF-8"; - - return super.finishImpl(context, outcome); - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "post"); - } - - @Override - public boolean getFinishButtonDisabled() - { - return true; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/forums/CreateReplyDialog.java b/war/src/main/java/org/alfresco/web/bean/forums/CreateReplyDialog.java deleted file mode 100644 index cada3b68dc..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/forums/CreateReplyDialog.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.forums; - -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.web.app.Application; -import org.alfresco.web.ui.common.Utils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean implementation of the "Create Reply Dialog". - * - * @author gavinc - */ -public class CreateReplyDialog extends CreatePostDialog -{ - private static final long serialVersionUID = 8036934269090933533L; - - protected String replyContent = null; - - private static final Log logger = LogFactory.getLog(CreateReplyDialog.class); - - // ------------------------------------------------------------------------------ - // Wizard implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - this.replyContent = null; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - // remove link breaks and replace with
- this.content = Utils.replaceLineBreaks(this.content, false); - - super.finishImpl(context, outcome); - - // setup the referencing aspect with the references association - // between the new post and the one being replied to - this.getNodeService().addAspect(this.createdNode, ContentModel.ASPECT_REFERENCING, null); - this.getNodeService().createAssociation(this.createdNode, this.browseBean.getDocument().getNodeRef(), - ContentModel.ASSOC_REFERENCES); - - if (logger.isDebugEnabled()) - { - logger.debug("created new node: " + this.createdNode); - logger.debug("existing node: " + this.browseBean.getDocument().getNodeRef()); - } - - return outcome; - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "reply"); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/forums/CreateTopicDialog.java b/war/src/main/java/org/alfresco/web/bean/forums/CreateTopicDialog.java deleted file mode 100644 index 5f1403b8cf..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/forums/CreateTopicDialog.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.forums; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.model.ForumModel; -import org.alfresco.service.cmr.model.FileInfo; -import org.alfresco.service.cmr.repository.ContentService; -import org.alfresco.service.cmr.repository.ContentWriter; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.spaces.CreateSpaceDialog; -import org.alfresco.web.ui.common.Utils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean implementation of the "Create Topic Dialog". - * - * @author gavinc - */ -public class CreateTopicDialog extends CreateSpaceDialog -{ - private static final long serialVersionUID = -8672220556613430308L; - - protected String message; - transient private ContentService contentService; - - private static final Log logger = LogFactory.getLog(CreateTopicDialog.class); - - // ------------------------------------------------------------------------------ - // Wizard implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - this.spaceType = ForumModel.TYPE_TOPIC.toString(); - this.message = null; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - super.finishImpl(context, outcome); - - // do topic specific processing - - // get the node ref of the node that will contain the content - NodeRef containerNodeRef = this.createdNode; - - // create a unique file name for the message content - String fileName = ForumsBean.createPostFileName(); - - FileInfo fileInfo = this.getFileFolderService().create(containerNodeRef, - fileName, ForumModel.TYPE_POST); - NodeRef postNodeRef = fileInfo.getNodeRef(); - - if (logger.isDebugEnabled()) - logger.debug("Created post node with filename: " + fileName); - - // apply the titled aspect - title and description - Map titledProps = new HashMap(3, 1.0f); - titledProps.put(ContentModel.PROP_TITLE, fileName); - this.getNodeService().addAspect(postNodeRef, ContentModel.ASPECT_TITLED, titledProps); - - if (logger.isDebugEnabled()) - logger.debug("Added titled aspect with properties: " + titledProps); - - Map editProps = new HashMap(1, 1.0f); - editProps.put(ApplicationModel.PROP_EDITINLINE, true); - this.getNodeService().addAspect(postNodeRef, ApplicationModel.ASPECT_INLINEEDITABLE, editProps); - - if (logger.isDebugEnabled()) - logger.debug("Added inlineeditable aspect with properties: " + editProps); - - // get a writer for the content and put the file - ContentWriter writer = getContentService().getWriter(postNodeRef, ContentModel.PROP_CONTENT, true); - // set the mimetype and encoding - writer.setMimetype(Repository.getMimeTypeForFileName(context, fileName)); - writer.setEncoding("UTF-8"); - writer.putContent(Utils.replaceLineBreaks(this.message, false)); - - return outcome; - } - - @Override - protected String doPostCommitProcessing(FacesContext context, String outcome) - { - // if the creation was successful we need to simulate a user - // selecting the topic, the dispatching will take us to the - // correct view. - this.browseBean.clickSpace(this.createdNode); - - return outcome + AlfrescoNavigationHandler.OUTCOME_SEPARATOR + "showTopic"; - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "create_topic"); - } - - // ------------------------------------------------------------------------------ - // Bean Getters and Setters - - /** - * Returns the message entered by the user for the first post - * - * @return The message for the first post - */ - public String getMessage() - { - return this.message; - } - - /** - * Sets the message - * - * @param message The message - */ - public void setMessage(String message) - { - this.message = message; - } - - // ------------------------------------------------------------------------------ - // Service Injection - - /** - * @param contentService The contentService to set. - */ - public void setContentService(ContentService contentService) - { - this.contentService = contentService; - } - - protected ContentService getContentService() - { - if (contentService == null) - { - contentService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getContentService(); - } - return contentService; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/forums/DeleteForumDialog.java b/war/src/main/java/org/alfresco/web/bean/forums/DeleteForumDialog.java deleted file mode 100644 index 9ff34823d6..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/forums/DeleteForumDialog.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.forums; - -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ForumModel; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.spaces.DeleteSpaceDialog; - -/** - * Bean implementation for the "Delete Forum" dialog - * - * @author gavinc - */ -public class DeleteForumDialog extends DeleteSpaceDialog -{ - private static final long serialVersionUID = -4246549059188399460L; - - protected boolean reDisplayForums; - - // ------------------------------------------------------------------------------ - // Dialog implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - // reset the reDisplayForums flag - this.reDisplayForums = false; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - // find out what the parent type of the node being deleted - Node node = this.browseBean.getActionSpace(); - NodeRef parent = null; - ChildAssociationRef assoc = this.getNodeService().getPrimaryParent(node.getNodeRef()); - if (assoc != null) - { - // get the parent node - parent = assoc.getParentRef(); - - // if the parent type is a forum space then we need the dialog to go - // back to the forums view otherwise it will use the default of 'browse', - // this happens when a forum being used to discuss a node is deleted. - QName parentType = this.getNodeService().getType(parent); - if (parentType.equals(ForumModel.TYPE_FORUMS)) - { - this.reDisplayForums = true; - } - } - - // delete the forum itself - outcome = super.finishImpl(context, outcome); - - // remove the discussable aspect if appropriate - if (assoc != null && parent != null) - { - // get the association type - QName type = assoc.getTypeQName(); - if (type.equals(ForumModel.ASSOC_DISCUSSION)) - { - // if the association type is the 'discussion' association we - // need to remove the discussable aspect from the parent node - this.getNodeService().removeAspect(parent, ForumModel.ASPECT_DISCUSSABLE); - } - } - - return outcome; - } - - @Override - protected String doPostCommitProcessing(FacesContext context, String outcome) - { - outcome = super.doPostCommitProcessing(context, outcome); - - if (this.reDisplayForums) - { - return AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME + - AlfrescoNavigationHandler.OUTCOME_SEPARATOR + "forumDeleted"; - } - else - { - return outcome; - } - } - - /** - * Returns the message bundle id of the confirmation message to display to - * the user before deleting the forum. - * - * @return The message bundle id - */ - @Override - protected String getConfirmMessageId() - { - return "delete_forum_confirm"; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/forums/DeleteForumsDialog.java b/war/src/main/java/org/alfresco/web/bean/forums/DeleteForumsDialog.java deleted file mode 100644 index 8fe692022f..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/forums/DeleteForumsDialog.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.forums; - -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ForumModel; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.spaces.DeleteSpaceDialog; - -/** - * Bean implementation for the "Delete Forum Space" dialog - * - * @author gavinc - */ -public class DeleteForumsDialog extends DeleteSpaceDialog -{ - private static final long serialVersionUID = -1673691210425371041L; - - protected boolean reDisplayForums; - - // ------------------------------------------------------------------------------ - // Dialog implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - // reset the reDisplayForums flag - this.reDisplayForums = false; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - // find out what the parent type of the node being deleted - Node node = this.browseBean.getActionSpace(); - ChildAssociationRef assoc = this.getNodeService().getPrimaryParent(node.getNodeRef()); - if (assoc != null) - { - NodeRef parent = assoc.getParentRef(); - QName parentType = this.getNodeService().getType(parent); - if (parentType.equals(ForumModel.TYPE_FORUMS)) - { - this.reDisplayForums = true; - } - } - - return super.finishImpl(context, outcome); - } - - @Override - protected String doPostCommitProcessing(FacesContext context, String outcome) - { - outcome = super.doPostCommitProcessing(context, outcome); - - if (this.reDisplayForums) - { - return AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME + - AlfrescoNavigationHandler.OUTCOME_SEPARATOR + "forumsDeleted"; - } - else - { - return outcome; - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/forums/DeletePostDialog.java b/war/src/main/java/org/alfresco/web/bean/forums/DeletePostDialog.java deleted file mode 100644 index d33e9c8bf1..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/forums/DeletePostDialog.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.forums; - -import java.text.MessageFormat; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.content.DeleteContentDialog; - -/** - * Bean implementation for the "Delete Post" dialog. - * - * @author gavinc - */ -public class DeletePostDialog extends DeleteContentDialog -{ - // ------------------------------------------------------------------------------ - // Dialog implementation - - private static final long serialVersionUID = 6804626884508461423L; - - @Override - protected String doPostCommitProcessing(FacesContext context, String outcome) - { - super.doPostCommitProcessing(context, outcome); - - return this.getDefaultFinishOutcome(); - } - - // ------------------------------------------------------------------------------ - // Bean Getters and Setters - - /** - * Returns the confirmation to display to the user before deleting the content. - * - * @return The formatted message to display - */ - public String getConfirmMessage() - { - String postConfirmMsg = Application.getMessage(FacesContext.getCurrentInstance(), - "delete_post_confirm"); - - return MessageFormat.format(postConfirmMsg, - new Object[] {this.browseBean.getDocument().getProperties().get("creator")}); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/forums/DeleteTopicDialog.java b/war/src/main/java/org/alfresco/web/bean/forums/DeleteTopicDialog.java deleted file mode 100644 index 1543d9080b..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/forums/DeleteTopicDialog.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.forums; - -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ForumModel; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.spaces.DeleteSpaceDialog; - -/** - * Bean implementation for the "Delete Topic" dialog - * - * @author gavinc - */ -public class DeleteTopicDialog extends DeleteSpaceDialog -{ - private static final long serialVersionUID = 548182341698381545L; - - protected boolean reDisplayTopics; - - // ------------------------------------------------------------------------------ - // Dialog implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - // reset the reDisplayTopics flag - this.reDisplayTopics = false; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - // find out what the parent type of the node being deleted - Node node = this.browseBean.getActionSpace(); - ChildAssociationRef assoc = this.getNodeService().getPrimaryParent(node.getNodeRef()); - if (assoc != null) - { - NodeRef parent = assoc.getParentRef(); - QName parentType = this.getNodeService().getType(parent); - if (parentType.equals(ForumModel.TYPE_FORUM)) - { - this.reDisplayTopics = true; - } - } - - return super.finishImpl(context, outcome); - } - - @Override - protected String doPostCommitProcessing(FacesContext context, String outcome) - { - outcome = super.doPostCommitProcessing(context, outcome); - - if (this.reDisplayTopics) - { - return AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME + - AlfrescoNavigationHandler.OUTCOME_SEPARATOR + "topicDeleted"; - } - else - { - return outcome; - } - } - - /** - * Returns the message bundle id of the confirmation message to display to - * the user before deleting the topic. - * - * @return The message bundle id - */ - @Override - protected String getConfirmMessageId() - { - return "delete_topic_confirm"; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/forums/EditPostDialog.java b/war/src/main/java/org/alfresco/web/bean/forums/EditPostDialog.java deleted file mode 100644 index a1b89ea371..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/forums/EditPostDialog.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.forums; - -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.repository.ContentReader; -import org.alfresco.service.cmr.repository.ContentWriter; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.ui.common.Utils; -import org.springframework.util.StringUtils; - -/** - * Bean implementation for the "Edit Post Dialog". - * - * @author gavinc - */ -public class EditPostDialog extends CreatePostDialog -{ - // ------------------------------------------------------------------------------ - // Wizard implementation - - private static final long serialVersionUID = 7925794441178897699L; - - @Override - public void init(Map parameters) - { - super.init(parameters); - - // we need to remove the
tags and replace with carriage returns - // and then setup the content member variable - Node currentDocument = this.browseBean.getDocument(); - ContentReader reader = this.getContentService().getReader(currentDocument.getNodeRef(), - ContentModel.PROP_CONTENT); - - if (reader != null) - { - String htmlContent = reader.getContentString(); - if (htmlContent != null) - { - // ETHREEOH-1216: replace both forms of 'br' as older posts have the
version - // which doesn't work in all browsers supported by Alfresco Explorer - htmlContent = StringUtils.replace(htmlContent, "
", "\r\n"); - this.content = StringUtils.replace(htmlContent, "
", "\r\n"); - } - } - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - // remove link breaks and replace with
- this.content = Utils.replaceLineBreaks(this.content, false); - - // update the content - NodeRef postNode = this.browseBean.getDocument().getNodeRef(); - - // check that the name of this post does not contain the : - // character (used in previous versions), if it does rename - // the post. - String name = (String)this.getNodeService().getProperty( - postNode, ContentModel.PROP_NAME); - if (name.indexOf(":") != -1) - { - String newName = name.replace(':', '-'); - this.getFileFolderService().rename(postNode, newName); - } - - ContentWriter writer = this.getContentService().getWriter(postNode, - ContentModel.PROP_CONTENT, true); - if (writer != null) - { - writer.putContent(this.content); - } - - return outcome; - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "ok"); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/forums/ForumDetailsDialog.java b/war/src/main/java/org/alfresco/web/bean/forums/ForumDetailsDialog.java deleted file mode 100644 index c86d83a999..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/forums/ForumDetailsDialog.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.forums; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.TemplateService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.BaseDetailsBean; -import org.alfresco.web.bean.dialog.NavigationSupport; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.NodeListUtils; -import org.alfresco.web.ui.common.NodePropertyComparator; -import org.alfresco.web.ui.common.component.UIActionLink; - -public class ForumDetailsDialog extends BaseDetailsBean implements NavigationSupport -{ - - private static final long serialVersionUID = -1358474435876806449L; - - private static final String MSG_DETAILS_OF = "details_of"; - private static final String MSG_LOCATION = "location"; - private final static String MSG_CLOSE = "close"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - /** - * Returns the Space this bean is currently representing - * - * @return The Space Node - */ - public Node getSpace() - { - return getNode(); - } - - @Override - protected Node getLinkResolvedNode() - { - Node space = getSpace(); - if (ApplicationModel.TYPE_FOLDERLINK.equals(space.getType())) - { - NodeRef destRef = (NodeRef) space.getProperties().get(ContentModel.PROP_LINK_DESTINATION); - if (getNodeService().exists(destRef)) - { - space = new Node(destRef); - } - } - return space; - } - - @Override - public Node getNode() - { - return this.browseBean.getActionSpace(); - } - - @Override - protected String getPropertiesPanelId() - { - return "space-props"; - } - - @Override - public Map getTemplateModel() - { - HashMap model = new HashMap(1, 1.0f); - - model.put("space", getSpace().getNodeRef()); - model.put(TemplateService.KEY_IMAGE_RESOLVER, imageResolver); - - return model; - - } - - /** - * Action handler to clear the current Space properties before returning to the browse screen, as the user may have modified the properties! - */ - public String cancel() - { - this.navigator.resetCurrentNodeProperties(); - return super.cancel(); - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - public String getCurrentItemId() - { - return getId(); - } - - public String getOutcome() - { - return "dialog:close:dialog:showSpaceDetails"; - } - - public void nextItem(ActionEvent event) - { - UIActionLink link = (UIActionLink) event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - NodeRef currNodeRef = new NodeRef(Repository.getStoreRef(), id); - List nodes = this.browseBean.getParentNodes(currNodeRef); - Node next = null; - if (nodes.size() > 1) - { - String currentSortColumn = this.browseBean.getSpacesRichList().getCurrentSortColumn(); - boolean currentSortDescending = this.browseBean.getSpacesRichList().isCurrentSortDescending(); - Collections.sort(nodes, new NodePropertyComparator(currentSortColumn, !currentSortDescending)); - next = NodeListUtils.nextItem(nodes, id); - this.browseBean.setupSpaceAction(next.getId(), false); - } - if (next == null) - { - Node currNode = new Node(currNodeRef); - this.navigator.setupDispatchContext(currNode); - } - } - - } - - public void previousItem(ActionEvent event) - { - UIActionLink link = (UIActionLink) event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - NodeRef currNodeRef = new NodeRef(Repository.getStoreRef(), id); - List nodes = this.browseBean.getParentNodes(currNodeRef); - Node previous = null; - if (nodes.size() > 1) - { - String currentSortColumn = this.browseBean.getSpacesRichList().getCurrentSortColumn(); - boolean currentSortDescending = this.browseBean.getSpacesRichList().isCurrentSortDescending(); - Collections.sort(nodes, new NodePropertyComparator(currentSortColumn, !currentSortDescending)); - previous = NodeListUtils.previousItem(nodes, id); - this.browseBean.setupSpaceAction(previous.getId(), false); - } - if (previous == null) - { - Node currNode = new Node(currNodeRef); - this.navigator.setupDispatchContext(currNode); - } - } - - } - - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } - - @Override - public String getContainerSubTitle() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_LOCATION) + ": " + - getSpace().getNodePath().toDisplayPath(getNodeService(), getPermissionService()); - } - - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_DETAILS_OF) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) + getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/forums/ForumsBean.java b/war/src/main/java/org/alfresco/web/bean/forums/ForumsBean.java deleted file mode 100644 index a4bfbe4056..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/forums/ForumsBean.java +++ /dev/null @@ -1,1351 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.forums; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.text.MessageFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; -import javax.faces.event.ActionEvent; -import javax.transaction.UserTransaction; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.model.ContentModel; -import org.alfresco.model.ForumModel; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.dictionary.TypeDefinition; -import org.alfresco.service.cmr.repository.AssociationRef; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.ContentReader; -import org.alfresco.service.cmr.repository.ContentService; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.search.QueryParameterDefinition; -import org.alfresco.service.cmr.search.SearchService; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.service.namespace.RegexQNamePattern; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.IContextListener; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.bean.BrowseBean; -import org.alfresco.web.bean.NavigationBean; -import org.alfresco.web.bean.repository.MapNode; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.NodePropertyResolver; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.config.ViewsConfigElement; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.alfresco.web.ui.common.component.UIModeList; -import org.alfresco.web.ui.common.component.data.UIColumn; -import org.alfresco.web.ui.common.component.data.UIRichList; -import org.alfresco.web.ui.common.renderer.data.IRichListRenderer; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean providing properties and behaviour for the forums screens. - * - * @author gavinc - */ -public class ForumsBean implements IContextListener -{ - private static final long serialVersionUID = 7066410060288061436L; - - private static Log logger = LogFactory.getLog(ForumsBean.class); - private static final String PAGE_NAME_FORUMS = "forums"; - private static final String PAGE_NAME_FORUM = "forum"; - private static final String PAGE_NAME_TOPIC = "topic"; - - /** The NodeService to be used by the bean */ - transient private NodeService nodeService; - - /** The ContentService to be used by the bean */ - transient private ContentService contentService; - - /** The DictionaryService bean reference */ - transient private DictionaryService dictionaryService; - - /** The SearchService bean reference. */ - transient private SearchService searchService; - - /** The NamespaceService bean reference. */ - transient private NamespaceService namespaceService; - - /** The browse bean */ - protected BrowseBean browseBean; - - /** The NavigationBean bean reference */ - protected NavigationBean navigator; - - /** Views configuration object */ - protected ViewsConfigElement viewsConfig = null; - - /** Component references */ - protected UIRichList forumsRichList; - protected UIRichList forumRichList; - protected UIRichList topicRichList; - - /** Node lists */ - private List forums; - private List topics; - private List posts; - - /** The current forums view mode - set to a well known IRichListRenderer identifier */ - private String forumsViewMode; - - /** The current forums view page size */ - private int forumsPageSize; - - /** The current forum view mode - set to a well known IRichListRenderer identifier */ - private String forumViewMode; - - /** The current forum view page size */ - private int forumPageSize; - - /** The current topic view mode - set to a well known IRichListRenderer identifier */ - private String topicViewMode; - - /** The current topic view page size */ - private int topicPageSize; - - - // ------------------------------------------------------------------------------ - // Construction - - /** - * Default Constructor - */ - public ForumsBean() - { - UIContextService.getInstance(FacesContext.getCurrentInstance()).registerBean(this); - - initFromClientConfig(); - } - - - // ------------------------------------------------------------------------------ - // Bean property getters and setters - - /** - * @param nodeService The NodeService to set. - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - protected NodeService getNodeService() - { - if (nodeService == null) - { - nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - } - return nodeService; - } - - /** - * Sets the content service to use - * - * @param contentService The ContentService - */ - public void setContentService(ContentService contentService) - { - this.contentService = contentService; - } - - protected ContentService getContentService() - { - if (contentService == null) - { - contentService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getContentService(); - } - return contentService; - } - - /** - * @param dictionaryService The DictionaryService to set. - */ - public void setDictionaryService(DictionaryService dictionaryService) - { - this.dictionaryService = dictionaryService; - } - - protected DictionaryService getDictionaryService() - { - if (dictionaryService == null) - { - dictionaryService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getDictionaryService(); - } - return dictionaryService; - } - - /** - * @param searchService The SearchService to set. - */ - public void setSearchService(SearchService searchService) - { - this.searchService = searchService; - } - - protected SearchService getSearchService() - { - if (searchService == null) - { - searchService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getSearchService(); - } - return searchService; - } - - /** - * @param namespaceService The NamespaceService to set. - */ - public void setNamespaceService(NamespaceService namespaceService) - { - this.namespaceService = namespaceService; - } - - protected NamespaceService getNamespaceService() - { - if (namespaceService == null) - { - namespaceService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNamespaceService(); - } - return namespaceService; - } - - /** - * Sets the BrowseBean instance to use to retrieve the current document - * - * @param browseBean BrowseBean instance - */ - public void setBrowseBean(BrowseBean browseBean) - { - this.browseBean = browseBean; - } - - /** - * @param navigator The NavigationBean to set. - */ - public void setNavigator(NavigationBean navigator) - { - this.navigator = navigator; - } - - /** - * @param forumsRichList The forumsRichList to set. - */ - public void setForumsRichList(UIRichList forumsRichList) - { - this.forumsRichList = forumsRichList; - if (this.forumsRichList != null) - { - // set the initial sort column and direction - this.forumsRichList.setInitialSortColumn( - this.viewsConfig.getDefaultSortColumn(PAGE_NAME_FORUMS)); - this.forumsRichList.setInitialSortDescending( - this.viewsConfig.hasDescendingSort(PAGE_NAME_FORUMS)); - - // ETWOONE-183 & ETWOONE-339. For URL addressability of forums spaces - this.forumsRichList.setRefreshOnBind(true); - } - } - - /** - * @return Returns the forumsRichList. - */ - public UIRichList getForumsRichList() - { - return this.forumsRichList; - } - - /** - * @return Returns the forums View mode. See UIRichList - */ - public String getForumsViewMode() - { - return this.forumsViewMode; - } - - /** - * @param forumsViewMode The forums View mode to set. See UIRichList. - */ - public void setForumsViewMode(String forumsViewMode) - { - this.forumsViewMode = forumsViewMode; - } - - /** - * @return Returns the forumsPageSize. - */ - public int getForumsPageSize() - { - return this.forumsPageSize; - } - - /** - * @param forumsPageSize The forumsPageSize to set. - */ - public void setForumsPageSize(int forumsPageSize) - { - this.forumsPageSize = forumsPageSize; - } - - /** - * @param topicRichList The topicRichList to set. - */ - public void setTopicRichList(UIRichList topicRichList) - { - this.topicRichList = topicRichList; - - if (this.topicRichList != null) - { - // set the initial sort column and direction - this.topicRichList.setInitialSortColumn( - this.viewsConfig.getDefaultSortColumn(PAGE_NAME_TOPIC)); - this.topicRichList.setInitialSortDescending( - this.viewsConfig.hasDescendingSort(PAGE_NAME_TOPIC)); - - // ETWOONE-183. For URL addressability of topics: - this.topicRichList.setRefreshOnBind(true); - } - } - - /** - * @return Returns the topicRichList. - */ - public UIRichList getTopicRichList() - { - return this.topicRichList; - } - - /** - * @return Returns the topics View mode. See UIRichList - */ - public String getTopicViewMode() - { - return this.topicViewMode; - } - - /** - * @param topicViewMode The topic View mode to set. See UIRichList. - */ - public void setTopicViewMode(String topicViewMode) - { - this.topicViewMode = topicViewMode; - } - - /** - * @return Returns the topicsPageSize. - */ - public int getTopicPageSize() - { - return this.topicPageSize; - } - - /** - * @param topicPageSize The topicPageSize to set. - */ - public void setTopicPageSize(int topicPageSize) - { - this.topicPageSize = topicPageSize; - } - - /** - * @param forumRichList The forumRichList to set. - */ - public void setForumRichList(UIRichList forumRichList) - { - this.forumRichList = forumRichList; - - if (this.forumRichList != null) - { - // set the initial sort column and direction - this.forumRichList.setInitialSortColumn( - this.viewsConfig.getDefaultSortColumn(PAGE_NAME_FORUM)); - this.forumRichList.setInitialSortDescending( - this.viewsConfig.hasDescendingSort(PAGE_NAME_FORUM)); - - // ETWOONE-183 & ETWOONE-339. For URL addressability of forum spaces - this.forumRichList.setRefreshOnBind(true); - } - } - - /** - * @return Returns the forumRichList. - */ - public UIRichList getForumRichList() - { - return this.forumRichList; - } - - /** - * @return Returns the forum View mode. See UIRichList - */ - public String getForumViewMode() - { - return this.forumViewMode; - } - - /** - * @param forumViewMode The forum View mode to set. See UIRichList. - */ - public void setForumViewMode(String forumViewMode) - { - this.forumViewMode = forumViewMode; - } - - /** - * @return Returns the forumPageSize. - */ - public int getForumPageSize() - { - return this.forumPageSize; - } - - /** - * @param forumPageSize The forumPageSize to set. - */ - public void setForumPageSize(int forumPageSize) - { - this.forumPageSize = forumPageSize; - } - - public List getForums() - { - if (this.forums == null) - { - getNodes(); - } - - return this.forums; - } - - public List getTopics() - { - if (this.topics == null) - { - getNodes(); - } - - return this.topics; - } - - public List getPosts() - { - if (this.posts == null) - { - getNodes(); - } - - return this.posts; - } - - private void getNodes() - { - long startTime = 0; - if (logger.isDebugEnabled()) - startTime = System.currentTimeMillis(); - - UserTransaction tx = null; - try - { - FacesContext context = FacesContext.getCurrentInstance(); - tx = Repository.getUserTransaction(context, true); - tx.begin(); - - // get the current space from NavigationBean - String parentNodeId = this.navigator.getCurrentNodeId(); - - NodeRef parentRef; - if (parentNodeId == null) - { - // no specific parent node specified - use the root node - parentRef = this.getNodeService().getRootNode(Repository.getStoreRef()); - } - else - { - // build a NodeRef for the specified Id and our store - parentRef = new NodeRef(Repository.getStoreRef(), parentNodeId); - } - - List childRefs = this.getNodeService().getChildAssocs(parentRef, - ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL); - this.forums = new ArrayList(childRefs.size()); - this.topics = new ArrayList(childRefs.size()); - this.posts = new ArrayList(childRefs.size()); - - for (ChildAssociationRef ref: childRefs) - { - // create our Node representation from the NodeRef - NodeRef nodeRef = ref.getChildRef(); - - if (this.getNodeService().exists(nodeRef)) - { - // find it's type so we can see if it's a node we are interested in - QName type = this.getNodeService().getType(nodeRef); - - // make sure the type is defined in the data dictionary - TypeDefinition typeDef = this.getDictionaryService().getType(type); - - if (typeDef != null) - { - // extract forums, forum, topic and post types - - if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_SYSTEM_FOLDER) == false) - { - if (this.getDictionaryService().isSubClass(type, ForumModel.TYPE_FORUMS) || - this.getDictionaryService().isSubClass(type, ForumModel.TYPE_FORUM)) - { - // create our Node representation - MapNode node = new MapNode(nodeRef, this.getNodeService(), true); - node.addPropertyResolver("icon", this.browseBean.resolverSpaceIcon); - node.addPropertyResolver("smallIcon", this.browseBean.resolverSmallIcon); - - this.forums.add(node); - } - if (this.getDictionaryService().isSubClass(type, ForumModel.TYPE_TOPIC)) - { - // create our Node representation - MapNode node = new MapNode(nodeRef, this.getNodeService(), true); - node.addPropertyResolver("icon", this.browseBean.resolverSpaceIcon); - node.addPropertyResolver("smallIcon", this.browseBean.resolverSmallIcon); - node.addPropertyResolver("replies", this.resolverReplies); - - this.topics.add(node); - } - else if (this.getDictionaryService().isSubClass(type, ForumModel.TYPE_POST)) - { - // create our Node representation - MapNode node = new MapNode(nodeRef, this.getNodeService(), true); - - this.browseBean.setupCommonBindingProperties(node); - node.addPropertyResolver("smallIcon", this.browseBean.resolverSmallIcon); - node.addPropertyResolver("message", this.resolverContent); - node.addPropertyResolver("replyTo", this.resolverReplyTo); - - this.posts.add(node); - } - } - } - else - { - if (logger.isWarnEnabled()) - logger.warn("Found invalid object in database: id = " + nodeRef + ", type = " + type); - } - } - } - - // commit the transaction - tx.commit(); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {refErr.getNodeRef()}) ); - this.forums = Collections.emptyList(); - this.topics = Collections.emptyList(); - this.posts = Collections.emptyList(); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err); - this.forums = Collections.emptyList(); - this.topics = Collections.emptyList(); - this.posts = Collections.emptyList(); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - - if (logger.isDebugEnabled()) - { - long endTime = System.currentTimeMillis(); - logger.debug("Time to query and build forums nodes: " + (endTime - startTime) + "ms"); - } - } - - /** - * Returns the HTML to represent a bubble rendition of the text of the the - * forum article being replied to. - * - * @return The HTML for the bubble - */ - public String getReplyBubbleHTML() - { - try - { - // if the forum being replied to was a new post show the orange bubble - // with the user on the left otherwise show the yellow bubble with the - // user on the right. - StringWriter writer = new StringWriter(); - - FacesContext context = FacesContext.getCurrentInstance(); - Node replyToNode = this.browseBean.getDocument(); - boolean isReplyPost = this.getNodeService().hasAspect(replyToNode.getNodeRef(), - ContentModel.ASPECT_REFERENCING); - String contextPath = context.getExternalContext().getRequestContextPath(); - String colour = isReplyPost ? "yellow" : "orange"; - String bgColour = isReplyPost ? "#FFF5A3" : "#FCC75E"; - - // build the HTML to represent the user that posted the article being replied to - StringBuilder replyPosterHTML = new StringBuilder(""); - replyPosterHTML.append("
"); - replyPosterHTML.append((String)replyToNode.getProperties().get("creator")); - replyPosterHTML.append(""); - - // start the table - writer.write(""); - - if (isReplyPost) - { - renderReplyContentHTML(context, replyToNode, writer, contextPath, colour, bgColour); - writer.write(replyPosterHTML.toString()); - } - else - { - writer.write(replyPosterHTML.toString()); - renderReplyContentHTML(context, replyToNode, writer, contextPath, colour, bgColour); - } - - // finish the table - writer.write("
"); - - return writer.toString(); - } - catch (IOException ioe) - { - throw new AlfrescoRuntimeException("Failed to render reply bubble HTML", ioe); - } - } - - // ------------------------------------------------------------------------------ - // IContextListener implementation - - /** - * @see org.alfresco.web.app.context.IContextListener#contextUpdated() - */ - public void contextUpdated() - { - if (logger.isDebugEnabled()) - logger.debug("Invalidating forums components..."); - - // clear the value for the list components - will cause re-bind to it's data and refresh - if (this.forumsRichList != null) - { - this.forumsRichList.setValue(null); - if (this.forumsRichList.getInitialSortColumn() == null) - { - // set the initial sort column and direction - this.forumsRichList.setInitialSortColumn( - this.viewsConfig.getDefaultSortColumn(PAGE_NAME_FORUMS)); - this.forumsRichList.setInitialSortDescending( - this.viewsConfig.hasDescendingSort(PAGE_NAME_FORUMS)); - } - } - - if (this.forumRichList != null) - { - this.forumRichList.setValue(null); - if (this.forumRichList.getInitialSortColumn() == null) - { - // set the initial sort column and direction - this.forumRichList.setInitialSortColumn( - this.viewsConfig.getDefaultSortColumn(PAGE_NAME_FORUM)); - this.forumRichList.setInitialSortDescending( - this.viewsConfig.hasDescendingSort(PAGE_NAME_FORUM)); - } - } - - if (this.topicRichList != null) - { - this.topicRichList.setValue(null); - if (this.topicRichList.getInitialSortColumn() == null) - { - // set the initial sort column and direction - this.topicRichList.setInitialSortColumn( - this.viewsConfig.getDefaultSortColumn(PAGE_NAME_TOPIC)); - this.topicRichList.setInitialSortDescending( - this.viewsConfig.hasDescendingSort(PAGE_NAME_TOPIC)); - } - } - - // reset the lists - this.forums = null; - this.topics = null; - this.posts = null; - } - - /** - * @see org.alfresco.web.app.context.IContextListener#areaChanged() - */ - public void areaChanged() - { - // nothing to do - } - - /** - * @see org.alfresco.web.app.context.IContextListener#spaceChanged() - */ - public void spaceChanged() - { - // nothing to do - } - - // ------------------------------------------------------------------------------ - // Navigation action event handlers - - /** - * Change the current forums view mode based on user selection - * - * @param event ActionEvent - */ - public void forumsViewModeChanged(ActionEvent event) - { - UIModeList viewList = (UIModeList)event.getComponent(); - - // get the view mode ID - String viewMode = viewList.getValue().toString(); - - // push the view mode into the lists - setForumsViewMode(viewMode); - - // get the default for the forum page - this.forumsPageSize = this.viewsConfig.getDefaultPageSize(PAGE_NAME_FORUMS, - this.forumsViewMode); - - if (logger.isDebugEnabled()) - logger.debug("Set default forums page size to: " + this.forumsPageSize); - } - - /** - * Change the current forum view mode based on user selection - * - * @param event ActionEvent - */ - public void forumViewModeChanged(ActionEvent event) - { - UIModeList viewList = (UIModeList)event.getComponent(); - - // get the view mode ID - String viewMode = viewList.getValue().toString(); - - // push the view mode into the lists - setForumViewMode(viewMode); - - // get the default for the forum page - this.forumPageSize = this.viewsConfig.getDefaultPageSize(PAGE_NAME_FORUM, - this.forumViewMode); - - if (logger.isDebugEnabled()) - logger.debug("Set default forum page size to: " + this.forumPageSize); - } - - /** - * Change the current topic view mode based on user selection - * - * @param event ActionEvent - */ - public void topicViewModeChanged(ActionEvent event) - { - UIModeList viewList = (UIModeList)event.getComponent(); - - // get the view mode ID - String viewMode = viewList.getValue().toString(); - - // push the view mode into the lists - setTopicViewMode(viewMode); - - // change the default page size if necessary - this.topicPageSize = this.viewsConfig.getDefaultPageSize(PAGE_NAME_TOPIC, - this.topicViewMode); - - if (logger.isDebugEnabled()) - logger.debug("Set default topic page size to: " + this.topicPageSize); - } - - /** - * Event handler called when a user wants to view or participate - * in a discussion on an object - * - * @param event ActionEvent - */ - public void discuss(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id == null || id.length() == 0) - { - throw new AlfrescoRuntimeException("discuss called without an id"); - } - - FacesContext context = FacesContext.getCurrentInstance(); - - NodeRef nodeRef = new NodeRef(Repository.getStoreRef(), id); - - if (this.getNodeService().hasAspect(nodeRef, ForumModel.ASPECT_DISCUSSABLE) == false) - { - throw new AlfrescoRuntimeException("discuss called for an object that does not have a discussion!"); - } - - // as the node has the discussable aspect there must be a discussions child assoc - List children = this.getNodeService().getChildAssocs(nodeRef, - ForumModel.ASSOC_DISCUSSION, RegexQNamePattern.MATCH_ALL); - - // there should only be one child, retrieve it if there is - if (children.size() == 1) - { - // show the forum for the discussion - NodeRef forumNodeRef = children.get(0).getChildRef(); - this.browseBean.clickSpace(forumNodeRef); - context.getApplication().getNavigationHandler().handleNavigation(context, null, "showForum"); - } - else - { - // this should never happen as the action evaluator should stop the action - // from displaying, just in case print a warning to the console - logger.warn("Node has the discussable aspect but does not have 1 child, it has " + - children.size() + " children!"); - } - } - - // ------------------------------------------------------------------------------ - // Property Resolvers - - public NodePropertyResolver resolverReplies = new NodePropertyResolver() { - private static final long serialVersionUID = -4800772273246202885L; - - public Object get(Node node) - { - // query for the number of posts within the given node - String repliesXPath = "./*[(subtypeOf('" + ForumModel.TYPE_POST + "'))]"; - List replies = getSearchService().selectNodes( - node.getNodeRef(), - repliesXPath, - new QueryParameterDefinition[] {}, - getNamespaceService(), - false); - - // reduce the count by 1 as one of the posts will be the initial post - int noReplies = replies.size() - 1; - - if (noReplies < 0) - { - noReplies = 0; - } - - return new Integer(noReplies); - } - }; - - public NodePropertyResolver resolverContent = new NodePropertyResolver() { - private static final long serialVersionUID = -2575377410105460440L; - - public Object get(Node node) - { - String content = null; - - // get the content property from the node and retrieve the - // full content as a string (obviously should only be used - // for small amounts of content) - ContentReader reader = getContentService().getReader(node.getNodeRef(), - ContentModel.PROP_CONTENT); - - if (reader != null) - { - content = Utils.stripUnsafeHTMLTags(reader.getContentString()); - } - - return content; - } - }; - - public NodePropertyResolver resolverReplyTo = new NodePropertyResolver() { - private static final long serialVersionUID = 2614901755220899360L; - - public Object get(Node node) - { - // determine if this node is a reply to another post, if so find - // the creator of the original poster - String replyTo = null; - - List assocs = getNodeService().getTargetAssocs(node.getNodeRef(), - ContentModel.ASSOC_REFERENCES); - - // there should only be one association, if there is more than one - // just get the first one - if (assocs.size() > 0) - { - AssociationRef assoc = assocs.get(0); - NodeRef target = assoc.getTargetRef(); - Node targetNode = new Node(target); - replyTo = (String)targetNode.getProperties().get("creator"); - } - - return replyTo; - } - }; - - /** - * Creates a file name for the message being posted - * - * @return The file name for the post - */ - public static String createPostFileName() - { - StringBuilder name = new StringBuilder("posted-"); - - // add a timestamp - SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss"); - name.append(dateFormat.format(new Date())); - - // add Universal Unique Identifier - // fix bugs ETWOONE-196 and ETWOONE-203 - name.append("-" + UUID.randomUUID()); - - // add the HTML file extension - name.append(".html"); - - return name.toString(); - } - - - // ------------------------------------------------------------------------------ - // Helpers - - /** - * Initialise default values from client configuration - */ - private void initFromClientConfig() - { - // TODO - review implications of these default values for dynamic/MT client - this.viewsConfig = (ViewsConfigElement)Application.getConfigService( - FacesContext.getCurrentInstance()).getConfig("Views"). - getConfigElement(ViewsConfigElement.CONFIG_ELEMENT_ID); - - // get the defaults for the forums page - this.forumsViewMode = this.viewsConfig.getDefaultView(PAGE_NAME_FORUMS); - this.forumsPageSize = this.viewsConfig.getDefaultPageSize(PAGE_NAME_FORUMS, - this.forumsViewMode); - - // get the default for the forum page - this.forumViewMode = this.viewsConfig.getDefaultView(PAGE_NAME_FORUM); - this.forumPageSize = this.viewsConfig.getDefaultPageSize(PAGE_NAME_FORUM, - this.forumViewMode); - - // get the default for the topic page - this.topicViewMode = this.viewsConfig.getDefaultView(PAGE_NAME_TOPIC); - this.topicPageSize = this.viewsConfig.getDefaultPageSize(PAGE_NAME_TOPIC, - this.topicViewMode); - - if (logger.isDebugEnabled()) - { - logger.debug("Set default forums view mode to: " + this.forumsViewMode); - logger.debug("Set default forums page size to: " + this.forumsPageSize); - logger.debug("Set default forum view mode to: " + this.forumViewMode); - logger.debug("Set default forum page size to: " + this.forumPageSize); - logger.debug("Set default topic view mode to: " + this.topicViewMode); - logger.debug("Set default topic page size to: " + this.topicPageSize); - } - } - - protected void renderReplyContentHTML(FacesContext context, - Node replyToNode, StringWriter writer, - String contextPath, String colour, String bgColour) - throws IOException - { - // get the content of the article being replied to - String replyContent = ""; - ContentReader reader = this.getContentService().getReader(replyToNode.getNodeRef(), - ContentModel.PROP_CONTENT); - if (reader != null) - { - replyContent = Utils.stripUnsafeHTMLTags(reader.getContentString()); - } - - // get the date of the article being replied to - String postedDate = Utils.getDateTimeFormat(context). - format(replyToNode.getProperties().get("created")); - - // generate the HTML - writer.write(""); - TopicBubbleViewRenderer.renderBubbleTop(writer, contextPath, colour, bgColour); - writer.write(""); - writer.write(Application.getMessage(context, "posted")); - writer.write(": "); - writer.write(postedDate); - TopicBubbleViewRenderer.renderBubbleMiddle(writer, contextPath, colour); - writer.write(replyContent); - TopicBubbleViewRenderer.renderBubbleBottom(writer, contextPath, colour); - writer.write(""); - } - - /** - * Class to implement a bubble view for the RichList component used in the topics screen - * - * @author gavinc - */ - public static class TopicBubbleViewRenderer implements IRichListRenderer - { - private static final long serialVersionUID = -6641033880549363822L; - - public static final String VIEWMODEID = "bubble"; - - public String getViewModeID() - { - return VIEWMODEID; - } - - public void renderListBefore(FacesContext context, UIRichList richList, UIColumn[] columns) - throws IOException - { - // nothing to do - } - - public void renderListRow(FacesContext context, UIRichList richList, UIColumn[] columns, Object row) - throws IOException - { - ResponseWriter out = context.getResponseWriter(); - - // find primary column (which must exist) and the actions column (which doesn't - // have to exist) - UIColumn primaryColumn = null; - UIColumn actionsColumn = null; - for (int i = 0; i < columns.length; i++) - { - if (columns[i].isRendered()) - { - if (columns[i].getPrimary()) - { - primaryColumn = columns[i]; - } - else if (columns[i].getActions()) - { - actionsColumn = columns[i]; - } - } - } - - if (primaryColumn == null) - { - if (logger.isWarnEnabled()) - logger.warn("No primary column found for RichList definition: " + richList.getId()); - } - - out.write(""); - - Node node = (Node)row; - if (node.getProperties().get("replyTo") == null) - { - renderNewPostBubble(context, out, node, primaryColumn, actionsColumn, columns); - } - else - { - renderReplyToBubble(context, out, node, primaryColumn, actionsColumn, columns); - } - - out.write(""); - - // add a little padding - out.write("
"); - } - - public void renderListAfter(FacesContext context, UIRichList richList, UIColumn[] columns) - throws IOException - { - ResponseWriter out = context.getResponseWriter(); - - out.write(""); - for (Iterator i = richList.getChildren().iterator(); i.hasNext(); /**/) - { - // output all remaining child components that are not UIColumn - UIComponent child = (UIComponent)i.next(); - if (child instanceof UIColumn == false) - { - Utils.encodeRecursive(context, child); - } - } - out.write(""); - } - - /** - * Renders the top part of the bubble i.e. before the header - * - * @param out The writer to output to - * @param contextPath Context path of the application - * @param colour The colour of the bubble - * @param titleBgColour Background colour of the header area - */ - public static void renderBubbleTop(Writer out, String contextPath, - String colour, String titleBgColour) throws IOException - { - out.write(""); - out.write(""); - out.write(""); - out.write(""); - out.write(""); - out.write(""); - out.write(""); - out.write(""); - out.write(""); - out.write(""); - out.write(""); - out.write(""); - out.write(""); - out.write(""); - out.write(""); - out.write(""); - out.write("
"); - } - - /** - * Renders the middle part of the bubble i.e. after the header and before the body - * - * @param out The writer to output to - * @param contextPath Context path of the application - * @param colour The colour of the bubble - */ - public static void renderBubbleMiddle(Writer out, String contextPath, String colour) - throws IOException - { - out.write("
"); - } - - /** - * Renders the bottom part of the bubble i.e. after the body - * - * @param out The writer to output to - * @param contextPath Context path of the application - * @param colour The colour of the bubble - */ - public static void renderBubbleBottom(Writer out, String contextPath, String colour) - throws IOException - { - out.write("
"); - } - - /** - * Renders the new post speech bubble - * - * @param context Faces context - * @param out The response writer - * @param node The Node for the row being rendered - * @param primaryColumn The primary column containing the message content - * @param actionsColumn The actions column containing all the actions - * @param columns All configured columns - */ - private void renderNewPostBubble(FacesContext context, ResponseWriter out, Node node, - UIColumn primaryColumn, UIColumn actionsColumn, UIColumn[] columns) throws IOException - { - String contextPath = context.getExternalContext().getRequestContextPath(); - String colour = "orange"; - - out.write(""); - out.write("

"); - out.write((String)node.getProperties().get("creator")); - out.write("
"); - - renderBubbleTop(out, contextPath, colour, "#FCC75E"); - renderHeaderContents(context, out, primaryColumn, actionsColumn, columns); - renderBubbleMiddle(out, contextPath, colour); - renderBodyContents(context, primaryColumn); - renderBubbleBottom(out, contextPath, colour); - - out.write("
"); - } - - /** - * Renders the reply to post speech bubble - * - * @param context Faces context - * @param out The response writer - * @param node The Node for the row being rendered - * @param primaryColumn The primary column containing the message content - * @param actionsColumn The actions column containing all the actions - * @param columns All configured columns - */ - private void renderReplyToBubble(FacesContext context, ResponseWriter out, Node node, - UIColumn primaryColumn, UIColumn actionsColumn, UIColumn[] columns) throws IOException - { - String contextPath = context.getExternalContext().getRequestContextPath(); - String colour = "yellow"; - - out.write(""); - out.write("
"); - - renderBubbleTop(out, contextPath, colour, "#FFF5A3"); - renderHeaderContents(context, out, primaryColumn, actionsColumn, columns); - renderBubbleMiddle(out, contextPath, colour); - renderBodyContents(context, primaryColumn); - renderBubbleBottom(out, contextPath, colour); - - out.write("
"); - out.write((String)node.getProperties().get("creator")); - out.write("
"); - } - - private void renderHeaderContents(FacesContext context, ResponseWriter out, - UIColumn primaryColumn, UIColumn actionsColumn, UIColumn[] columns) throws IOException - { - // render the header area with the configured columns - out.write(""); - - for (int i = 0; i < columns.length; i++) - { - UIColumn column = columns[i]; - - if (column.isRendered() == true && - column.getPrimary() == false && - column.getActions() == false) - { - // render the column header as the label - UIComponent header = column.getFacet("header"); - if (header != null) - { - out.write(""); - } - - // render the contents of the column - if (column.getChildCount() != 0) - { - out.write(""); - } - } - } - - // render the actions column - out.write("
"); - Utils.encodeRecursive(context, header); - out.write(""); - Utils.encodeRecursive(context, column); - out.write(""); - if (actionsColumn != null && actionsColumn.getChildCount() != 0) - { - Utils.encodeRecursive(context, actionsColumn); - } - out.write("
"); - } - - /** - * Renders the body contents for the bubble using the given primary coumn - * - * @param context Faces context - * @param primaryColumn The primary column holding the message text - */ - private void renderBodyContents(FacesContext context, UIColumn primaryColumn) - throws IOException - { - // render the primary column - if (primaryColumn != null && primaryColumn.getChildCount() != 0) - { - Utils.encodeRecursive(context, primaryColumn); - } - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/forums/ForumsDetailsDialog.java b/war/src/main/java/org/alfresco/web/bean/forums/ForumsDetailsDialog.java deleted file mode 100644 index 6c357b3da3..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/forums/ForumsDetailsDialog.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.forums; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.TemplateService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.BaseDetailsBean; -import org.alfresco.web.bean.dialog.NavigationSupport; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.NodeListUtils; -import org.alfresco.web.ui.common.NodePropertyComparator; -import org.alfresco.web.ui.common.component.UIActionLink; - -public class ForumsDetailsDialog extends BaseDetailsBean implements NavigationSupport -{ - - private static final long serialVersionUID = 279622505413904654L; - - private static final String MSG_DETAILS_OF = "details_of"; - private static final String MSG_LOCATION = "location"; - private final static String MSG_CLOSE = "close"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - /** - * Returns the Space this bean is currently representing - * - * @return The Space Node - */ - public Node getSpace() - { - return getNode(); - } - - @Override - protected Node getLinkResolvedNode() - { - Node space = getSpace(); - if (ApplicationModel.TYPE_FOLDERLINK.equals(space.getType())) - { - NodeRef destRef = (NodeRef) space.getProperties().get(ContentModel.PROP_LINK_DESTINATION); - if (getNodeService().exists(destRef)) - { - space = new Node(destRef); - } - } - return space; - } - - @Override - public Node getNode() - { - return this.browseBean.getActionSpace(); - } - - @Override - protected String getPropertiesPanelId() - { - return "space-props"; - } - - @Override - public Map getTemplateModel() - { - HashMap model = new HashMap(1, 1.0f); - - model.put("space", getSpace().getNodeRef()); - model.put(TemplateService.KEY_IMAGE_RESOLVER, imageResolver); - - return model; - - } - - /** - * Action handler to clear the current Space properties before returning to the browse screen, as the user may have modified the properties! - */ - public String cancel() - { - this.navigator.resetCurrentNodeProperties(); - return super.cancel(); - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - public String getCurrentItemId() - { - return getId(); - } - - public String getOutcome() - { - return "dialog:close:dialog:showSpaceDetails"; - } - - public void nextItem(ActionEvent event) - { - UIActionLink link = (UIActionLink) event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - NodeRef currNodeRef = new NodeRef(Repository.getStoreRef(), id); - List nodes = this.browseBean.getParentNodes(currNodeRef); - Node next = null; - if (nodes.size() > 1) - { - String currentSortColumn = this.browseBean.getSpacesRichList().getCurrentSortColumn(); - boolean currentSortDescending = this.browseBean.getSpacesRichList().isCurrentSortDescending(); - Collections.sort(nodes, new NodePropertyComparator(currentSortColumn, !currentSortDescending)); - next = NodeListUtils.nextItem(nodes, id); - this.browseBean.setupSpaceAction(next.getId(), false); - } - if (next == null) - { - Node currNode = new Node(currNodeRef); - this.navigator.setupDispatchContext(currNode); - } - } - - } - - public void previousItem(ActionEvent event) - { - UIActionLink link = (UIActionLink) event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - NodeRef currNodeRef = new NodeRef(Repository.getStoreRef(), id); - List nodes = this.browseBean.getParentNodes(currNodeRef); - Node previous = null; - if (nodes.size() > 1) - { - String currentSortColumn = this.browseBean.getSpacesRichList().getCurrentSortColumn(); - boolean currentSortDescending = this.browseBean.getSpacesRichList().isCurrentSortDescending(); - Collections.sort(nodes, new NodePropertyComparator(currentSortColumn, !currentSortDescending)); - previous = NodeListUtils.previousItem(nodes, id); - this.browseBean.setupSpaceAction(previous.getId(), false); - } - if (previous == null) - { - Node currNode = new Node(currNodeRef); - this.navigator.setupDispatchContext(currNode); - } - } - - } - - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } - - @Override - public String getContainerSubTitle() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_LOCATION) + ": " + - getSpace().getNodePath().toDisplayPath(getNodeService(), getPermissionService()); - } - - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_DETAILS_OF) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) + getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/forums/TopicDetailsDialog.java b/war/src/main/java/org/alfresco/web/bean/forums/TopicDetailsDialog.java deleted file mode 100644 index e979844d4a..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/forums/TopicDetailsDialog.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.forums; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.TemplateService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.BaseDetailsBean; -import org.alfresco.web.bean.dialog.NavigationSupport; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.NodeListUtils; -import org.alfresco.web.ui.common.NodePropertyComparator; -import org.alfresco.web.ui.common.component.UIActionLink; - -public class TopicDetailsDialog extends BaseDetailsBean implements NavigationSupport -{ - - private static final long serialVersionUID = -5879020614355773789L; - - private static final String MSG_DETAILS_OF = "details_of"; - private static final String MSG_LOCATION = "location"; - private final static String MSG_CLOSE = "close"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - /** - * Returns the Space this bean is currently representing - * - * @return The Space Node - */ - public Node getSpace() - { - return getNode(); - } - - @Override - protected Node getLinkResolvedNode() - { - Node space = getSpace(); - if (ApplicationModel.TYPE_FOLDERLINK.equals(space.getType())) - { - NodeRef destRef = (NodeRef) space.getProperties().get(ContentModel.PROP_LINK_DESTINATION); - if (getNodeService().exists(destRef)) - { - space = new Node(destRef); - } - } - return space; - } - - @Override - public Node getNode() - { - return this.browseBean.getActionSpace(); - } - - @Override - protected String getPropertiesPanelId() - { - return "space-props"; - } - - @Override - public Map getTemplateModel() - { - HashMap model = new HashMap(1, 1.0f); - - model.put("space", getSpace().getNodeRef()); - model.put(TemplateService.KEY_IMAGE_RESOLVER, imageResolver); - - return model; - - } - - /** - * Action handler to clear the current Space properties before returning to the browse screen, as the user may have modified the properties! - */ - public String cancel() - { - this.navigator.resetCurrentNodeProperties(); - return super.cancel(); - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - public String getCurrentItemId() - { - return getId(); - } - - public String getOutcome() - { - return "dialog:close:dialog:showSpaceDetails"; - } - - public void nextItem(ActionEvent event) - { - UIActionLink link = (UIActionLink) event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - NodeRef currNodeRef = new NodeRef(Repository.getStoreRef(), id); - List nodes = this.browseBean.getParentNodes(currNodeRef); - Node next = null; - if (nodes.size() > 1) - { - String currentSortColumn = this.browseBean.getSpacesRichList().getCurrentSortColumn(); - boolean currentSortDescending = this.browseBean.getSpacesRichList().isCurrentSortDescending(); - Collections.sort(nodes, new NodePropertyComparator(currentSortColumn, !currentSortDescending)); - next = NodeListUtils.nextItem(nodes, id); - this.browseBean.setupSpaceAction(next.getId(), false); - } - if (next == null) - { - Node currNode = new Node(currNodeRef); - this.navigator.setupDispatchContext(currNode); - } - } - - } - - public void previousItem(ActionEvent event) - { - UIActionLink link = (UIActionLink) event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - NodeRef currNodeRef = new NodeRef(Repository.getStoreRef(), id); - List nodes = this.browseBean.getParentNodes(currNodeRef); - Node previous = null; - if (nodes.size() > 1) - { - String currentSortColumn = this.browseBean.getSpacesRichList().getCurrentSortColumn(); - boolean currentSortDescending = this.browseBean.getSpacesRichList().isCurrentSortDescending(); - Collections.sort(nodes, new NodePropertyComparator(currentSortColumn, !currentSortDescending)); - previous = NodeListUtils.previousItem(nodes, id); - this.browseBean.setupSpaceAction(previous.getId(), false); - } - if (previous == null) - { - Node currNode = new Node(currNodeRef); - this.navigator.setupDispatchContext(currNode); - } - } - - } - - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } - - @Override - public String getContainerSubTitle() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_LOCATION) + ": " + - getSpace().getNodePath().toDisplayPath(getNodeService(), getPermissionService()); - } - - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_DETAILS_OF) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) + getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/generator/AjaxTagPickerGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/AjaxTagPickerGenerator.java deleted file mode 100644 index ba0859da9b..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/AjaxTagPickerGenerator.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; - -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.ui.repo.RepoConstants; -import org.alfresco.web.ui.repo.component.UIMultiValueEditor; -import org.alfresco.web.ui.repo.component.property.PropertySheetItem; -import org.alfresco.web.ui.repo.component.property.UIPropertySheet; - -/** - * Generates a category selector component. - * - * @author Mike Hatfield - */ -public class AjaxTagPickerGenerator extends BaseComponentGenerator -{ - public UIComponent generate(FacesContext context, String id) - { - UIComponent component = context.getApplication(). - createComponent(RepoConstants.ALFRESCO_FACES_AJAX_TAG_PICKER); - FacesHelper.setupComponentId(context, component, id); - - return component; - } - - @Override - @SuppressWarnings("unchecked") - protected UIComponent createComponent(FacesContext context, UIPropertySheet propertySheet, - PropertySheetItem item) - { - // the category selector component is used whatever mode the property sheet is in - return generate(context, item.getName()); - } - - @Override - protected void setupMandatoryValidation(FacesContext context, UIPropertySheet propertySheet, - PropertySheetItem item, UIComponent component, boolean realTimeChecking, String idSuffix) - { - if (component instanceof UIMultiValueEditor) - { - // Override the setup of the mandatory validation - // so we can send the _current_value id suffix. - // We also enable real time so the page load - // check disables the ok button if necessary, as the user - // adds or removes items from the multi value list the - // page will be refreshed and therefore re-check the status. - - super.setupMandatoryValidation(context, propertySheet, item, - component, true, "_current_value"); - } - else - { - // Override the setup of the mandatory validation - // so we can send the _selected id suffix. - // We also enable real time so the page load check disabled - // the ok button if necessary, as the control is used the - // page will be refreshed and therefore re-check the status. - - super.setupMandatoryValidation(context, propertySheet, item, - component, true, "_selected"); - } - } - - @Override - protected ControlType getControlType() - { - return ControlType.SELECTOR; - } - - @Override - protected UIComponent setupMultiValuePropertyIfNecessary( - FacesContext context, UIPropertySheet propertySheet, - PropertySheetItem property, PropertyDefinition propertyDef, - UIComponent component) - { - return component; - } - -} - diff --git a/war/src/main/java/org/alfresco/web/bean/generator/AssociationGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/AssociationGenerator.java deleted file mode 100644 index 198d571bde..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/AssociationGenerator.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.ui.repo.RepoConstants; -import org.alfresco.web.ui.repo.component.property.PropertySheetItem; -import org.alfresco.web.ui.repo.component.property.UIPropertySheet; - -/** - * Generates a component to manage associations. - * - * @author gavinc - */ -public class AssociationGenerator extends BaseComponentGenerator -{ - protected String optionsSize = null; - - public String getAvailableOptionsSize() - { - return this.optionsSize; - } - - public void setAvailableOptionsSize(String optionsSize) - { - this.optionsSize = optionsSize; - } - - @SuppressWarnings("unchecked") - public UIComponent generate(FacesContext context, String id) - { - UIComponent component = context.getApplication(). - createComponent(RepoConstants.ALFRESCO_FACES_ASSOC_EDITOR); - FacesHelper.setupComponentId(context, component, id); - - // set the size of the list (if provided) - if (this.optionsSize != null) - { - component.getAttributes().put("availableOptionsSize", this.optionsSize); - } - - return component; - } - - @Override - protected void setupMandatoryValidation(FacesContext context, UIPropertySheet propertySheet, - PropertySheetItem item, UIComponent component, boolean realTimeChecking, String idSuffix) - { - // Override the setup of the mandatory validation - // so we can send the _current_value id suffix. - // We also enable real time so the page load - // check disables the ok button if necessary, as the user - // adds or removes items from the multi value list the - // page will be refreshed and therefore re-check the status. - // Only so this however id the component is not read-only - - if (item.isReadOnly() == false) - { - super.setupMandatoryValidation(context, propertySheet, item, - component, true, "_current_value"); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/generator/BaseComponentGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/BaseComponentGenerator.java deleted file mode 100644 index c03ea68fe5..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/BaseComponentGenerator.java +++ /dev/null @@ -1,780 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.List; - -import javax.faces.FacesException; -import javax.faces.component.UIComponent; -import javax.faces.component.UIGraphic; -import javax.faces.component.UIOutput; -import javax.faces.context.FacesContext; -import javax.faces.convert.Converter; -import javax.faces.el.ValueBinding; - -import org.alfresco.repo.dictionary.constraint.ListOfValuesConstraint; -import org.alfresco.repo.dictionary.constraint.NumericRangeConstraint; -import org.alfresco.repo.dictionary.constraint.RegexConstraint; -import org.alfresco.repo.dictionary.constraint.StringLengthConstraint; -import org.alfresco.service.cmr.dictionary.AssociationDefinition; -import org.alfresco.service.cmr.dictionary.Constraint; -import org.alfresco.service.cmr.dictionary.ConstraintDefinition; -import org.alfresco.service.cmr.dictionary.DataTypeDefinition; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.repository.DataDictionary; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.ui.common.ComponentConstants; -import org.alfresco.web.ui.repo.RepoConstants; -import org.alfresco.web.ui.repo.component.UIMultiValueEditor; -import org.alfresco.web.ui.repo.component.property.BaseAssociationEditor; -import org.alfresco.web.ui.repo.component.property.PropertySheetItem; -import org.alfresco.web.ui.repo.component.property.UIProperty; -import org.alfresco.web.ui.repo.component.property.UIPropertySheet; -import org.alfresco.web.ui.repo.component.property.UISeparator; -import org.alfresco.web.ui.repo.component.property.UIPropertySheet.ClientValidation; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.util.StringUtils; -import org.springframework.web.jsf.FacesContextUtils; - -public abstract class BaseComponentGenerator implements IComponentGenerator -{ - private static Log logger = LogFactory.getLog(BaseComponentGenerator.class); - - protected enum ControlType { FIELD, SELECTOR; } - - protected DataDictionary dataDictionary; - - @SuppressWarnings("unchecked") - public UIComponent generateAndAdd(FacesContext context, UIPropertySheet propertySheet, - PropertySheetItem item) - { - UIComponent component = null; - - if (item instanceof UIProperty) - { - // get the property definition - PropertyDefinition propertyDef = getPropertyDefinition(context, - propertySheet.getNode(), item.getName()); - - // create the component and add it to the property sheet - component = createComponent(context, propertySheet, item); - - // setup the component for multi value editing if necessary - component = setupMultiValuePropertyIfNecessary(context, propertySheet, - item, propertyDef, component); - - // setup common aspects of the property i.e. value binding - setupProperty(context, propertySheet, item, propertyDef, component); - - // add the component now, it needs to be added before the validations - // are setup as we need access to the component id, which in turn needs - // to have a parent to get the correct id - item.getChildren().add(component); - - // setup the component for mandatory validation if necessary - setupMandatoryPropertyIfNecessary(context, propertySheet, item, - propertyDef, component); - - // setup any constraints the property has - setupConstraints(context, propertySheet, item, propertyDef, component); - - // setup any converter the property needs - setupConverter(context, propertySheet, item, propertyDef, component); - } - else if (item instanceof UISeparator) - { - // just create the component and add it - component = createComponent(context, propertySheet, item); - item.getChildren().add(component); - } - else - { - // get the association definition - AssociationDefinition assocationDef = this.getAssociationDefinition(context, - propertySheet.getNode(), item.getName()); - - // create the component and add it to the property sheet - component = createComponent(context, propertySheet, item); - - // setup common aspects of the association i.e. value binding - setupAssociation(context, propertySheet, item, assocationDef, component); - - // add the component now, it needs to be added before the validations - // are setup as we need access to the component id, which needs have a - // parent to get the correct id - item.getChildren().add(component); - - // setup the component for mandatory validation if necessary - setupMandatoryAssociationIfNecessary(context, propertySheet, item, - assocationDef, component); - - // setup any converter the association needs - setupConverter(context, propertySheet, item, assocationDef, component); - } - - return component; - } - - - /** - * Creates the component for the given proerty sheet item. - * - * @param context FacesContext - * @param propertySheet The property sheet being generated - * @param item The property or association being generated - * @return The newly created component - */ - @SuppressWarnings("unchecked") - protected UIComponent createComponent(FacesContext context, UIPropertySheet propertySheet, - PropertySheetItem item) - { - UIComponent component = null; - - if (item instanceof UIProperty) - { - if (propertySheet.inEditMode()) - { - // use the standard component in edit mode - component = generate(context, item.getName()); - } - else - { - // create an output text component in view mode - component = createOutputTextComponent(context, item.getName()); - } - } - else - { - // create the standard association component - component = generate(context, item.getName()); - } - - return component; - } - - /** - * Creates the converter with the given id and adds it to the component. - * - * @param context FacesContext - * @param converterId The name of the converter to create - * @param component The component to add the converter to - */ - protected void createAndSetConverter(FacesContext context, String converterId, - UIComponent component) - { - if (converterId != null && component instanceof UIOutput) - { - try - { - Converter conv = context.getApplication().createConverter(converterId); - ((UIOutput)component).setConverter(conv); - } - catch (NullPointerException npe) - { - // workaround a NPE bug in MyFaces - logger.warn("Converter " + converterId + " could not be applied"); - } - catch (FacesException fe) - { - logger.warn("Converter " + converterId + " could not be applied"); - } - } - } - - /** - * Creates an output text component. - * - * @param context FacesContext - * @param id Optional id to set - * @return The new component - */ - protected UIOutput createOutputTextComponent(FacesContext context, String id) - { - UIOutput component = (UIOutput)context.getApplication().createComponent( - ComponentConstants.JAVAX_FACES_OUTPUT); - - component.setRendererType(ComponentConstants.JAVAX_FACES_TEXT); - FacesHelper.setupComponentId(context, component, id); - - return component; - } - - /** - * Sets up the property component i.e. setting the value binding - * - * @param context FacesContext - * @param propertySheet The property sheet - * @param item The parent component - * @param propertyDef The property definition - * @param component The component representing the property - */ - @SuppressWarnings("unchecked") - protected void setupProperty(FacesContext context, UIPropertySheet propertySheet, - PropertySheetItem item, PropertyDefinition propertyDef, UIComponent component) - { - // create and set the value binding - ValueBinding vb = null; - - if (propertyDef != null) - { - vb = context.getApplication().createValueBinding( - "#{" + propertySheet.getVar() + ".properties[\"" + - propertyDef.getName().toString() + "\"]}"); - } - else - { - vb = context.getApplication().createValueBinding( - "#{" + propertySheet.getVar() + ".properties[\"" + - item.getName() + "\"]}"); - } - - component.setValueBinding("value", vb); - - // disable the component if it is read only or protected - // or if the property sheet is in view mode - if (propertySheet.inEditMode() == false || item.isReadOnly() || - (propertyDef != null && propertyDef.isProtected())) - { - component.getAttributes().put("disabled", Boolean.TRUE); - } - } - - /** - * Sets up the association component i.e. setting the value binding - * - * @param context FacesContext - * @param propertySheet The property sheet - * @param item The parent component - * @param associationDef The association definition - * @param component The component representing the association - */ - @SuppressWarnings("unchecked") - protected void setupAssociation(FacesContext context, UIPropertySheet propertySheet, - PropertySheetItem item, AssociationDefinition associationDef, UIComponent component) - { - // create and set the value binding - ValueBinding vb = context.getApplication().createValueBinding( - "#{" + propertySheet.getVar() + "}"); - component.setValueBinding("value", vb); - - // set the association name and set to disabled if appropriate - ((BaseAssociationEditor)component).setAssociationName( - associationDef.getName().toString()); - - // disable the component if it is read only or protected - // or if the property sheet is in view mode - if (propertySheet.inEditMode() == false || item.isReadOnly() || - (associationDef != null && associationDef.isProtected())) - { - component.getAttributes().put("disabled", Boolean.TRUE); - } - } - - /** - * Creates a wrapper component around the given component to enable the user - * to edit multiple values. - * - * @param context FacesContext - * @param propertySheet The property sheet being generated - * @param property The property being generated - * @param propertyDef The data dictionary definition for the property - * @param component The component representing the property - * @return A wrapped component if the property is multi-valued or the - * original component if it is not multi-valued - */ - @SuppressWarnings("unchecked") - protected UIComponent setupMultiValuePropertyIfNecessary(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem property, - PropertyDefinition propertyDef, UIComponent component) - { - UIComponent multiValueComponent = component; - - if (propertySheet.inEditMode() && property.isReadOnly() == false && - propertyDef != null && propertyDef.isProtected() == false && - propertyDef.isMultiValued()) - { - // if the property is multi-valued create a multi value editor wrapper component - String id = "multi_" + property.getName(); - multiValueComponent = context.getApplication().createComponent( - RepoConstants.ALFRESCO_FACES_MULTIVALUE_EDITOR); - FacesHelper.setupComponentId(context, multiValueComponent, id); - - // set the renderer depending on whether the item is a 'field' or a 'selector' - if (getControlType() == ControlType.FIELD) - { - multiValueComponent.setRendererType(RepoConstants.ALFRESCO_FACES_FIELD_RENDERER); - - // set flag to indicate the wrapped field is multilingual, if necessary - if (propertyDef.getDataType().getName().equals(DataTypeDefinition.MLTEXT)) - { - multiValueComponent.getAttributes().put("mltext", Boolean.TRUE); - } - } - else - { - multiValueComponent.setRendererType(RepoConstants.ALFRESCO_FACES_SELECTOR_RENDERER); - - // set the value binding for the wrapped component and the lastItemAdded attribute of - // the multi select component, needs to point somewhere that can hold any object, it - // will store the item last added by the user. - String expr = "#{MultiValueEditorBean.lastItemsAdded['" + - property.getName() + "']}"; - ValueBinding vb = context.getApplication().createValueBinding(expr); - multiValueComponent.setValueBinding("lastItemAdded", vb); - component.setValueBinding("value", vb); - } - - // add the original component as a child of the wrapper - multiValueComponent.getChildren().add(component); - } - - return multiValueComponent; - } - - /** - * Sets up a mandatory validation rule for the given property. - * - * @param context FacesContext - * @param propertySheet The property sheet being generated - * @param property The property being generated - * @param propertyDef The data dictionary definition of the property - * @param component The component representing the property - */ - @SuppressWarnings("unchecked") - protected void setupMandatoryPropertyIfNecessary(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem property, - PropertyDefinition propertyDef, UIComponent component) - { - // only setup validations if the property sheet is in edit mode, - // validation is enabled and the property is declared as mandatory - if (propertySheet.inEditMode() && propertySheet.isValidationEnabled() && - propertyDef != null && propertyDef.isMandatory()) - { - setupMandatoryValidation(context, propertySheet, property, component, false, null); - setupMandatoryMarker(context, property); - } - } - - /** - * Sets up a mandatory validation rule for the given association. - * - * @param context FacesContext - * @param propertySheet The property sheet being generated - * @param association The association being generated - * @param associationDef The data dictionary definition of the association - * @param component The component representing the association - */ - protected void setupMandatoryAssociationIfNecessary(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem association, - AssociationDefinition associationDef, UIComponent component) - { - // only setup validations if the property sheet is in edit mode, - // validation is enabled and the association is declared as mandatory - if (propertySheet.inEditMode() && propertySheet.isValidationEnabled() && - associationDef != null && associationDef.isTargetMandatory()) - { - setupMandatoryValidation(context, propertySheet, association, component, false, null); - setupMandatoryMarker(context, association); - } - } - - /** - * Sets up a client mandatory validation rule with the property - * sheet for the given item. - * - * @param context FacesContext - * @param propertySheet The property sheet to add the validation rule to - * @param item The item being generated - * @param component The component representing the item - * @param realTimeChecking true to make the client validate as the user types - * @param idSuffix An optional suffix to add to the client id - */ - protected void setupMandatoryValidation(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem item, - UIComponent component, boolean realTimeChecking, - String idSuffix) - { - List params = new ArrayList(3); - - // add the value parameter - StringBuilder value = new StringBuilder("document.getElementById('"); - value.append(component.getClientId(context)); - if (idSuffix != null) - { - value.append(idSuffix); - } - value.append("')"); - params.add(value.toString()); - - // add the validation failed message to show (use the value of the - // label component of the given item) - String msg = Application.getMessage(context, "validation_mandatory"); - addStringConstraintParam(params, - MessageFormat.format(msg, new Object[] {item.getResolvedDisplayLabel()})); - - // add the validation case to the property sheet - propertySheet.addClientValidation(new ClientValidation("validateMandatory", - params, realTimeChecking)); - } - - /** - * Sets up the marker to show that the item is mandatory. - * - * @param context FacesContext - * @param item The item being generated - */ - @SuppressWarnings("unchecked") - protected void setupMandatoryMarker(FacesContext context, PropertySheetItem item) - { - // create the required field graphic - UIGraphic image = (UIGraphic)context.getApplication(). - createComponent(UIGraphic.COMPONENT_TYPE); - image.setUrl("/images/icons/required_field.gif"); - image.getAttributes().put("style", "padding-right: 4px;"); - - // add marker as child to the property sheet item - item.getChildren().add(image); - } - - /** - * Sets up client validation rules for any constraints the property has. - * - * @param context FacesContext - * propertySheet The property sheet being generated - * @param property The property being generated - * @param propertyDef The data dictionary definition of the property - * @param component The component representing the property - */ - protected void setupConstraints(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem property, - PropertyDefinition propertyDef, UIComponent component) - { - // only setup constraints if the property sheet is in edit mode, - // validation is enabled - if (propertySheet.inEditMode() && propertySheet.isValidationEnabled() && - propertyDef != null) - { - List constraints = propertyDef.getConstraints(); - for (ConstraintDefinition constraintDef : constraints) - { - Constraint constraint = constraintDef.getConstraint(); - - if (constraint instanceof RegexConstraint) - { - setupRegexConstraint(context, propertySheet, property, component, - (RegexConstraint)constraint, false); - } - else if (constraint instanceof StringLengthConstraint) - { - setupStringLengthConstraint(context, propertySheet, property, component, - (StringLengthConstraint)constraint, false); - } - else if (constraint instanceof NumericRangeConstraint) - { - setupNumericRangeConstraint(context, propertySheet, property, component, - (NumericRangeConstraint)constraint, false); - } - else if (constraint instanceof ListOfValuesConstraint) - { - // NOTE: This is dealt with at the component creation stage - // as a different component is usually required. - } - } - } - } - - /** - * Sets up a default validation rule for the regular expression constraint - * - * @param context FacesContext - * @param propertySheet The property sheet to add the validation rule to - * @param property The property being generated - * @param component The component representing the property - * @param constraint The constraint to setup - * @param realTimeChecking true to make the client validate as the user types - */ - protected void setupRegexConstraint(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem property, - UIComponent component, RegexConstraint constraint, - boolean realTimeChecking) - { - String expression = constraint.getExpression(); - boolean requiresMatch = constraint.getRequiresMatch(); - - List params = new ArrayList(3); - - // add the value parameter - String value = "document.getElementById('" + - component.getClientId(context) + - (component instanceof UIMultiValueEditor ? "_current_value" : "") + - "')"; - params.add(value); - - // add the regular expression parameter - try - { - // encode the expression so it can be unescaped by JavaScript - addStringConstraintParam(params, URLEncoder.encode(expression, "UTF-8")); - } - catch (UnsupportedEncodingException e) - { - // just add the expression as is - addStringConstraintParam(params, expression); - } - - // add the requiresMatch parameter - params.add(Boolean.toString(requiresMatch)); - - // add the validation failed messages - String matchMsg = Application.getMessage(context, "validation_regex"); - addStringConstraintParam(params, - MessageFormat.format(matchMsg, new Object[] {property.getResolvedDisplayLabel()})); - - String noMatchMsg = Application.getMessage(context, "validation_regex_not_match"); - addStringConstraintParam(params, - MessageFormat.format(noMatchMsg, new Object[] {property.getResolvedDisplayLabel()})); - - // add the validation case to the property sheet - propertySheet.addClientValidation(new ClientValidation((component instanceof UIMultiValueEditor ? "validateMultivalueRegex" : "validateRegex"), - params, realTimeChecking)); - } - - /** - * Sets up a default validation rule for the string length constraint - * - * @param context FacesContext - * @param propertySheet The property sheet to add the validation rule to - * @param property The property being generated - * @param component The component representing the property - * @param constraint The constraint to setup - * @param realTimeChecking true to make the client validate as the user types - */ - protected void setupStringLengthConstraint(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem property, - UIComponent component, StringLengthConstraint constraint, - boolean realTimeChecking) - { - int min = constraint.getMinLength(); - int max = constraint.getMaxLength(); - - List params = new ArrayList(3); - - // add the value parameter - String value = "document.getElementById('" + - component.getClientId(context) + "')"; - params.add(value); - - // add the min parameter - params.add(Integer.toString(min)); - - // add the max parameter - params.add(Integer.toString(max)); - - // add the validation failed message to show - String msg = Application.getMessage(context, "validation_string_length"); - addStringConstraintParam(params, - MessageFormat.format(msg, new Object[] {property.getResolvedDisplayLabel(), min, max})); - - // add the validation case to the property sheet - propertySheet.addClientValidation(new ClientValidation("validateStringLength", - params, realTimeChecking)); - } - - /** - * Sets up a default validation rule for the numeric range constraint - * - * @param context FacesContext - * @param propertySheet The property sheet to add the validation rule to - * @param property The property being generated - * @param component The component representing the property - * @param constraint The constraint to setup - * @param realTimeChecking true to make the client validate as the user types - */ - protected void setupNumericRangeConstraint(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem property, - UIComponent component, NumericRangeConstraint constraint, - boolean realTimeChecking) - { - double min = constraint.getMinValue(); - double max = constraint.getMaxValue(); - - List params = new ArrayList(3); - - // add the value parameter - String value = "document.getElementById('" + - component.getClientId(context) + "')"; - params.add(value); - - // add the min parameter - params.add(Double.toString(min)); - - // add the max parameter - params.add(Double.toString(max)); - - // add the validation failed message to show - String msg = Application.getMessage(context, "validation_numeric_range"); - addStringConstraintParam(params, - MessageFormat.format(msg, new Object[] {property.getResolvedDisplayLabel(), min, max})); - - // add the validation case to the property sheet - propertySheet.addClientValidation(new ClientValidation("validateNumberRange", - params, false)); - } - - /** - * Sets up the appropriate converter for the given property - * - * @param context FacesContext - * @param propertySheet The property sheet being generated - * @param property The property being generated - * @param propertyDef The data dictionary definition of the property - * @param component The component representing the property - */ - protected void setupConverter(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem property, - PropertyDefinition propertyDef, UIComponent component) - { - if (property.getConverter() != null) - { - // create and add the custom converter - createAndSetConverter(context, property.getConverter(), component); - } - else if (propertySheet.inEditMode() == false && - propertyDef != null && propertyDef.isMultiValued()) - { - // if there isn't a custom converter and the property is - // multi-valued add the multi value converter as a default - createAndSetConverter(context, RepoConstants.ALFRESCO_FACES_MULTIVALUE_CONVERTER, - component); - } - } - - /** - * Sets up the appropriate converter for the given association - * - * @param context FacesContext - * @param propertySheet The property sheet being generated - * @param association The association being generated - * @param associationDef The data dictionary definition of the property - * @param component The component representing the association - */ - protected void setupConverter(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem association, - AssociationDefinition associationDef, UIComponent component) - { - if (association.getConverter() != null) - { - // create and add the custom converter - createAndSetConverter(context, association.getConverter(), component); - } - } - - /** - * Returns the type of the control being generated - * - * @return The type of the control either a FIELD or a SELECTOR - */ - protected ControlType getControlType() - { - return ControlType.FIELD; - } - - /** - * Retrieve the PropertyDefinition for the given property name on the given node - * - * @param node The node to get the property definition from - * @param propertyName The name of the property - * @return PropertyDefinition for the node or null if a definition can not be found - */ - protected PropertyDefinition getPropertyDefinition(FacesContext context, - Node node, String propertyName) - { - return getDataDictionary(context).getPropertyDefinition(node, propertyName); - } - - /** - * Retrieve the AssociationDefinition for the given property name on the given node - * - * @param node The node to get the association definition from - * @param associationName The name of the property - * @return AssociationDefinition for the node or null if a definition can not be found - */ - protected AssociationDefinition getAssociationDefinition(FacesContext context, - Node node, String associationName) - { - return getDataDictionary(context).getAssociationDefinition(node, associationName); - } - - /** - * Adds the given string parameter to the list of parameters to be used for - * validating constraints on the client. - * This method adds the quotes around the given parameter and also escapes - * any ocurrences of the double quote character. - * - * @param params The list of parameters for the constraint - * @param param The string parameter to add - */ - protected void addStringConstraintParam(List params, String param) - { - params.add("\"" + StringUtils.replace(param, "\"", "\\\"") + "\""); - } - - private DataDictionary getDataDictionary(FacesContext context) - { - if (this.dataDictionary == null) - { - this.dataDictionary = (DataDictionary)FacesContextUtils.getRequiredWebApplicationContext( - context).getBean(Application.BEAN_DATA_DICTIONARY); - } - - return this.dataDictionary; - } - - public boolean isEnabledInEditMode (FacesContext context, UIComponent control, PropertyDefinition propDef) - { - // get type info for the property - DataTypeDefinition dataTypeDef = propDef.getDataType(); - QName typeName = dataTypeDef.getName(); - if (typeName.equals(DataTypeDefinition.NODE_REF) || typeName.equals(DataTypeDefinition.PATH) || - typeName.equals(DataTypeDefinition.CONTENT) || typeName.equals(DataTypeDefinition.QNAME) || - typeName.equals(DataTypeDefinition.CHILD_ASSOC_REF) || typeName.equals(DataTypeDefinition.ASSOC_REF)) - { - return false; - } - else - { - return true; - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/generator/CategorySelectorGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/CategorySelectorGenerator.java deleted file mode 100644 index 4ac8a6565c..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/CategorySelectorGenerator.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.ui.repo.RepoConstants; -import org.alfresco.web.ui.repo.component.UIMultiValueEditor; -import org.alfresco.web.ui.repo.component.property.PropertySheetItem; -import org.alfresco.web.ui.repo.component.property.UIPropertySheet; - -/** - * Generates a category selector component. - * - * @author gavinc - */ -public class CategorySelectorGenerator extends BaseComponentGenerator -{ - public UIComponent generate(FacesContext context, String id) - { - UIComponent component = context.getApplication(). - createComponent(RepoConstants.ALFRESCO_FACES_CATEGORY_SELECTOR); - FacesHelper.setupComponentId(context, component, id); - - return component; - } - - @Override - @SuppressWarnings("unchecked") - protected UIComponent createComponent(FacesContext context, UIPropertySheet propertySheet, - PropertySheetItem item) - { - // the category selector component is used whatever mode the property sheet is in - return generate(context, item.getName()); - } - - @Override - protected void setupMandatoryValidation(FacesContext context, UIPropertySheet propertySheet, - PropertySheetItem item, UIComponent component, boolean realTimeChecking, String idSuffix) - { - if (component instanceof UIMultiValueEditor) - { - // Override the setup of the mandatory validation - // so we can send the _current_value id suffix. - // We also enable real time so the page load - // check disables the ok button if necessary, as the user - // adds or removes items from the multi value list the - // page will be refreshed and therefore re-check the status. - - super.setupMandatoryValidation(context, propertySheet, item, - component, true, "_current_value"); - } - else - { - // Override the setup of the mandatory validation - // so we can send the _selected id suffix. - // We also enable real time so the page load check disabled - // the ok button if necessary, as the control is used the - // page will be refreshed and therefore re-check the status. - - super.setupMandatoryValidation(context, propertySheet, item, - component, true, "_selected"); - } - } - - @Override - protected ControlType getControlType() - { - return ControlType.SELECTOR; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/generator/CharsetSelectorGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/CharsetSelectorGenerator.java deleted file mode 100644 index 35917430cb..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/CharsetSelectorGenerator.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; - -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.ui.repo.component.UICharsetSelector; -import org.alfresco.web.ui.repo.component.property.PropertySheetItem; -import org.alfresco.web.ui.repo.component.property.UIPropertySheet; -import org.alfresco.web.ui.repo.converter.CharsetConverter; - -/** - * Generates a Charset selector component. - * - * @since 2.1 - * @author Derek Hulley - */ -public class CharsetSelectorGenerator extends BaseComponentGenerator -{ - public UIComponent generate(FacesContext context, String id) - { - UIComponent component = context.getApplication().createComponent(UICharsetSelector.COMPONENT_TYPE); - FacesHelper.setupComponentId(context, component, id); - - return component; - } - - @Override - protected void setupConverter(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem property, - PropertyDefinition propertyDef, UIComponent component) - { - if (propertySheet.inEditMode() == false) - { - if (property.getConverter() != null) - { - // create and add the custom converter - createAndSetConverter(context, property.getConverter(), component); - } - else - { - // if there isn't a custom converter add the mime type converter as a default - createAndSetConverter(context, CharsetConverter.CONVERTER_ID, component); - } - } - } - - @Override - protected void setupMandatoryValidation(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem item, - UIComponent component, boolean realTimeChecking, String idSuffix) - { - // a mime type selector will always have one value or another - // so there is no need to create a mandatory validation rule. - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/generator/CheckboxGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/CheckboxGenerator.java deleted file mode 100644 index aae57b8c27..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/CheckboxGenerator.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; - -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.ui.common.ComponentConstants; -import org.alfresco.web.ui.common.converter.BooleanLabelConverter; -import org.alfresco.web.ui.repo.component.property.PropertySheetItem; -import org.alfresco.web.ui.repo.component.property.UIPropertySheet; - -/** - * Generates a checkbox component. - * - * @author gavinc - */ -public class CheckboxGenerator extends BaseComponentGenerator -{ - public UIComponent generate(FacesContext context, String id) - { - UIComponent component = context.getApplication(). - createComponent(ComponentConstants.JAVAX_FACES_SELECT_BOOLEAN); - component.setRendererType(ComponentConstants.JAVAX_FACES_CHECKBOX); - FacesHelper.setupComponentId(context, component, id); - - return component; - } - - @Override - protected void setupConverter(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem property, - PropertyDefinition propertyDef, UIComponent component) - { - if (property.getConverter() != null) - { - // create and add the custom converter - createAndSetConverter(context, property.getConverter(), component); - } - else - { - if (propertySheet.inEditMode() == false) - { - // if there isn't a custom converter add the boolean - // converter as a default - createAndSetConverter(context, BooleanLabelConverter.CONVERTER_ID, - component); - } - } - } - - @Override - protected void setupMandatoryValidation(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem item, - UIComponent component, boolean realTimeChecking, String idSuffix) - { - // a checkbox will always have one value or another so there - // is no need to create a mandatory validation rule - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/generator/ChildAssociationGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/ChildAssociationGenerator.java deleted file mode 100644 index 9084bda2f1..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/ChildAssociationGenerator.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.ui.repo.RepoConstants; -import org.alfresco.web.ui.repo.component.property.PropertySheetItem; -import org.alfresco.web.ui.repo.component.property.UIPropertySheet; - -/** - * Generates a component to manage child associations. - * - * @author gavinc - */ -public class ChildAssociationGenerator extends BaseComponentGenerator -{ - protected String optionsSize = null; - - public String getAvailableOptionsSize() - { - return this.optionsSize; - } - - public void setAvailableOptionsSize(String optionsSize) - { - this.optionsSize = optionsSize; - } - - @SuppressWarnings("unchecked") - public UIComponent generate(FacesContext context, String id) - { - UIComponent component = context.getApplication(). - createComponent(RepoConstants.ALFRESCO_FACES_CHILD_ASSOC_EDITOR); - FacesHelper.setupComponentId(context, component, id); - - // set the size of the list (if provided) - if (this.optionsSize != null) - { - component.getAttributes().put("availableOptionsSize", this.optionsSize); - } - - return component; - } - - @Override - protected void setupMandatoryValidation(FacesContext context, UIPropertySheet propertySheet, - PropertySheetItem item, UIComponent component, boolean realTimeChecking, String idSuffix) - { - // Override the setup of the mandatory validation - // so we can send the _current_value id suffix. - // We also enable real time so the page load - // check disables the ok button if necessary, as the user - // adds or removes items from the multi value list the - // page will be refreshed and therefore re-check the status. - // But only do this if the component is not read-only - - if (item.isReadOnly() == false) - { - super.setupMandatoryValidation(context, propertySheet, item, - component, true, "_current_value"); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/generator/DatePickerGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/DatePickerGenerator.java deleted file mode 100644 index 69baaccdfc..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/DatePickerGenerator.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import java.util.Calendar; - -import javax.faces.component.UIComponent; -import javax.faces.component.UIOutput; -import javax.faces.context.FacesContext; -import javax.faces.convert.Converter; - -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.ui.common.ComponentConstants; -import org.alfresco.web.ui.common.converter.XMLDateConverter; -import org.alfresco.web.ui.repo.RepoConstants; -import org.alfresco.web.ui.repo.component.UIMultiValueEditor; -import org.alfresco.web.ui.repo.component.property.PropertySheetItem; -import org.alfresco.web.ui.repo.component.property.UIPropertySheet; - -/** - * Generates a date picker component. - * - * @author gavinc - */ -public class DatePickerGenerator extends BaseComponentGenerator -{ - private boolean initialiseIfNull = false; - private int yearCount = 30; - private int startYear = Calendar.getInstance().get(Calendar.YEAR) + 2; - private String noneLabel = null; - - private static final String MSG_DATE = "date_pattern"; - - /** - * @return Returns the year to start counting back from - */ - public int getStartYear() - { - return startYear; - } - - /** - * @param startYear Sets the year to start counting back from - */ - public void setStartYear(int startYear) - { - this.startYear = startYear; - } - - /** - * @return Returns the number of years to show - */ - public int getYearCount() - { - return yearCount; - } - - /** - * @param yearCount Sets the number of years to show - */ - public void setYearCount(int yearCount) - { - this.yearCount = yearCount; - } - - /** - * @return Determines whether the control should initially show - * today's date if the model value is null - */ - public boolean isInitialiseIfNull() - { - return initialiseIfNull; - } - - /** - * @param initialiseIfNull Determines whether the control should - * initially show today's date if the model value is null. - * This will also hide the None button thus disallowing - * the user to set the date back to null. - */ - public void setInitialiseIfNull(boolean initialiseIfNull) - { - this.initialiseIfNull = initialiseIfNull; - } - - /** - * Returns the label to use when there is no date set. - * - * @return The 'None' label to use - */ - public String getNoneLabel() - { - return this.noneLabel; - } - - /** - * Sets the label to use when there is no date set. - * Setting this to null will use the default label. - * - * @param noneLabel The 'None' label - */ - public void setNoneLabel(String noneLabel) - { - this.noneLabel = noneLabel; - } - - @SuppressWarnings("unchecked") - public UIComponent generate(FacesContext context, String id) - { - UIComponent component = context.getApplication(). - createComponent(ComponentConstants.JAVAX_FACES_INPUT); - component.setRendererType(RepoConstants.ALFRESCO_FACES_DATE_PICKER_RENDERER); - FacesHelper.setupComponentId(context, component, id); - component.getAttributes().put("startYear", this.startYear); - component.getAttributes().put("yearCount", this.yearCount); - component.getAttributes().put("initialiseIfNull", new Boolean(this.initialiseIfNull)); - component.getAttributes().put("style", "margin-right: 7px;"); - if (this.noneLabel != null) - { - component.getAttributes().put("noneLabel", this.noneLabel); - } - - return component; - } - - @Override - protected void setupConverter(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem property, - PropertyDefinition propertyDef, UIComponent component) - { - if (property.getConverter() != null) - { - // create and add the custom converter - createAndSetConverter(context, property.getConverter(), component); - } - else - { - // use the default converter for the date component - // we can cast this as we know it is an UIOutput type - ((UIOutput)component).setConverter(getDefaultConverter(context)); - } - } - - @Override - protected void setupMandatoryValidation(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem item, - UIComponent component, boolean realTimeChecking, String idSuffix) - { - if (component instanceof UIMultiValueEditor) - { - // Override the setup of the mandatory validation - // so we can send the _current_value id suffix. - // We also enable real time so the page load - // check disables the ok button if necessary, as the user - // adds or removes items from the multi value list the - // page will be refreshed and therefore re-check the status. - - super.setupMandatoryValidation(context, propertySheet, item, - component, true, "_current_value"); - } - else - { - // setup the client validation rule with real time validation enabled - // so that the initial page load checks the state of the date - super.setupMandatoryValidation(context, propertySheet, item, - component, true, idSuffix); - } - - } - - /** - * Retrieves the default converter for the date component - * - * @param context FacesContext - * @return XMLDateConverter - */ - protected Converter getDefaultConverter(FacesContext context) - { - XMLDateConverter converter = (XMLDateConverter)context.getApplication(). - createConverter(RepoConstants.ALFRESCO_FACES_XMLDATE_CONVERTER); - converter.setType("date"); - converter.setPattern(Application.getMessage(context, MSG_DATE)); - return converter; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/generator/DateTimePickerGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/DateTimePickerGenerator.java deleted file mode 100644 index b200fe9d10..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/DateTimePickerGenerator.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.convert.Converter; - -import org.alfresco.web.app.Application; -import org.alfresco.web.ui.common.converter.XMLDateConverter; -import org.alfresco.web.ui.repo.RepoConstants; - -/** - * Generates a date time picker component. - * - * @author gavinc - */ -public class DateTimePickerGenerator extends DatePickerGenerator -{ - private static final String MSG_DATE_TIME = "date_time_pattern"; - - @SuppressWarnings("unchecked") - public UIComponent generate(FacesContext context, String id) - { - UIComponent component = super.generate(context, id); - - // add the attribute to show the time - component.getAttributes().put("showTime", Boolean.TRUE); - - return component; - } - - /** - * Retrieves the default converter for the date time component - * - * @param context FacesContext - * @return XMLDateConverter - */ - protected Converter getDefaultConverter(FacesContext context) - { - XMLDateConverter converter = (XMLDateConverter)context.getApplication(). - createConverter(RepoConstants.ALFRESCO_FACES_XMLDATE_CONVERTER); - converter.setType("both"); - converter.setPattern(Application.getMessage(context, MSG_DATE_TIME)); - return converter; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/generator/HeaderSeparatorGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/HeaderSeparatorGenerator.java deleted file mode 100644 index 5ee4a740b3..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/HeaderSeparatorGenerator.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import javax.faces.component.UIComponent; - -import org.alfresco.web.ui.repo.component.property.PropertySheetItem; - -/** - * Generates a component to represent a separator that gets rendered - * as a header. - * - * @author gavinc - */ -public class HeaderSeparatorGenerator extends SeparatorGenerator -{ - protected String getHtml(UIComponent component, PropertySheetItem item) - { - String html = "
 " + - item.getDisplayLabel() + "
"; - - return html; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/generator/HtmlSeparatorGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/HtmlSeparatorGenerator.java deleted file mode 100644 index 9f898a2d3e..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/HtmlSeparatorGenerator.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; - -import org.alfresco.web.ui.repo.component.property.PropertySheetItem; -import org.alfresco.web.ui.repo.component.property.UIPropertySheet; - -/** - * Generates a component to represent a separator. - *

The HTML to be used for the separator is configured via the - * setHtml method. - * - * @author gavinc - */ -public class HtmlSeparatorGenerator extends BaseComponentGenerator -{ - protected String html = ""; - - /** - * Returns the HTML configured to be used for this separator - * - * @return The HTML to display - */ - public String getHtml() - { - return html; - } - - /** - * Sets the HTML to display for the separator - * - * @param html The HTML - */ - public void setHtml(String html) - { - this.html = html; - } - - @SuppressWarnings("unchecked") - public UIComponent generate(FacesContext context, String id) - { - UIComponent component = this.createOutputTextComponent(context, id); - component.getAttributes().put("escape", Boolean.FALSE); - - return component; - } - - @Override - @SuppressWarnings("unchecked") - protected UIComponent createComponent(FacesContext context, UIPropertySheet propertySheet, - PropertySheetItem item) - { - UIComponent component = this.generate(context, item.getName()); - - // set the HTML to use - component.getAttributes().put("value", getResolvedHtml(component, item)); - - return component; - } - - /** - * Returns the resolved HTML to use for the separator. - *

In the default case we just return the HTML set - * via setHtml however subclasses may choose to generate - * the resulting HTML using a combination of the HTML set - * via setHtml and the given PropertySheetItem. - * - * @param component The JSF component representing the separator - * @param item The separator item - * @return The resolved HTML - */ - protected String getResolvedHtml(UIComponent component, PropertySheetItem item) - { - // In the default case we just return the HTML set via setHtml - - return this.html; - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/bean/generator/IComponentGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/IComponentGenerator.java deleted file mode 100644 index ce213fd8e6..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/IComponentGenerator.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; - -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.web.ui.repo.component.property.PropertySheetItem; -import org.alfresco.web.ui.repo.component.property.UIPropertySheet; - -/** - * Interface definition for objects that dynamically generate components. - * - * @author gavinc - */ -public interface IComponentGenerator -{ - /** - * Dynamically generates a component in a default state - * - * @param context FacesContext - * @param id Optional id for the newly created component, if null - * is passed a unique id is generated - * @return The component instance - */ - UIComponent generate(FacesContext context, String id); - - /** - * Dynamically generates a component for the given property sheet item. - * The generated component is also setup appropriately for it's model - * definition and added to the given property sheet. - * - * @param context FacesContext - * @param propertySheet The property sheet component - * @param item The wrappper component representing the item to generate, - * either a property, association or child association - * @return The component instance - */ - UIComponent generateAndAdd(FacesContext context, UIPropertySheet propertySheet, - PropertySheetItem item); - - /** - * Determines whether the component will be enabled when rendered. - * - * @param context FacesContext - * @param control The control being rendered - * @param propDef The definition of the property - * @return true if the component should be enabled - */ - boolean isEnabledInEditMode (FacesContext context, UIComponent control, PropertyDefinition propDef); -} diff --git a/war/src/main/java/org/alfresco/web/bean/generator/LabelGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/LabelGenerator.java deleted file mode 100644 index 4889257c59..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/LabelGenerator.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; - -import org.alfresco.web.ui.repo.component.property.PropertySheetItem; -import org.alfresco.web.ui.repo.component.property.UIPropertySheet; - -/** - * Generates a text field component to represent a label. - * - * @author gavinc - */ -public class LabelGenerator extends BaseComponentGenerator -{ - public UIComponent generate(FacesContext context, String id) - { - return createOutputTextComponent(context, id); - } - - @Override - @SuppressWarnings("unchecked") - public UIComponent generateAndAdd(FacesContext context, UIPropertySheet propertySheet, - PropertySheetItem item) - { - UIComponent component = generate(context, "label_" + item.getName()); - - // add the component to the property sheet item - item.getChildren().add(component); - - // TODO: setup the 'for' attribute to associate with it the control - - return component; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/generator/LabelSeparatorGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/LabelSeparatorGenerator.java deleted file mode 100644 index 0473292e23..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/LabelSeparatorGenerator.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import javax.faces.component.UIComponent; - -import org.alfresco.web.ui.repo.component.property.PropertySheetItem; - -/** - * Generates a component to represent a separator that uses the - * property sheet display label configuration. The CSS class used - * for the HTML representing the label can also be configured via - * the setStyleClass method. - * - * @author gavinc - */ -public class LabelSeparatorGenerator extends HtmlSeparatorGenerator -{ - protected String style = "margin-top: 6px; margin-bottom: 6px;"; - protected String styleClass; - - /** - * Returns the CSS class configured to be used for this separator - * - * @return The CSS class - */ - public String getStyleClass() - { - return styleClass; - } - - /** - * Sets the CSS class to use for the separator - * - * @param styleClass The CSS class - */ - public void setStyleClass(String styleClass) - { - this.styleClass = styleClass; - } - - /** - * Returns the CSS style configured to be used for this separator - * - * @return The CSS style - */ - public String getStyle() - { - return style; - } - - /** - * Sets the CSS style to use for the separator - * - * @param style The CSS style - */ - public void setStyle(String style) - { - this.style = style; - } - - @Override - protected String getResolvedHtml(UIComponent component, PropertySheetItem item) - { - StringBuilder htmlBuilder = new StringBuilder(" 0) - { - htmlBuilder.append(" class=\""); - htmlBuilder.append(this.styleClass); - htmlBuilder.append("\""); - } - - if (this.style != null && this.style.length() > 0) - { - htmlBuilder.append(" style=\""); - htmlBuilder.append(this.style); - htmlBuilder.append("\""); - } - - // add the display label and close the div - htmlBuilder.append("> "); - htmlBuilder.append(item.getDisplayLabel()); - htmlBuilder.append(""); - - return htmlBuilder.toString(); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/generator/LanguageSelectorGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/LanguageSelectorGenerator.java deleted file mode 100644 index 9849b3a3e7..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/LanguageSelectorGenerator.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import javax.faces.component.UIComponent; -import javax.faces.component.UISelectItems; -import javax.faces.component.UISelectOne; -import javax.faces.context.FacesContext; -import javax.faces.model.SelectItem; - -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.users.UserPreferencesBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.ui.repo.component.property.PropertySheetItem; -import org.alfresco.web.ui.repo.component.property.UIPropertySheet; -import org.alfresco.web.ui.repo.converter.LanguageConverter; - -/** - * Generates a LANGUAGE selector component. - * - * @author Yannick Pignot - */ -public class LanguageSelectorGenerator extends BaseComponentGenerator -{ - protected Node node; - - protected UserPreferencesBean userPreferencesBean; - - @SuppressWarnings("unchecked") - public UIComponent generate(FacesContext context, String id) - { - UIComponent component = context.getApplication(). - createComponent(UISelectOne.COMPONENT_TYPE); - FacesHelper.setupComponentId(context, component, id); - - // create the list of choices - UISelectItems itemsComponent = (UISelectItems)context.getApplication(). - createComponent("javax.faces.SelectItems"); - - itemsComponent.setValue(getLanguageItems()); - - // add the items as a child component - component.getChildren().add(itemsComponent); - - return component; - } - - protected SelectItem[] getLanguageItems() - { - SelectItem[] items = userPreferencesBean.getAvailablesContentFilterLanguages(node.getNodeRef(), true); - - return items; - } - - @Override - protected UIComponent createComponent(FacesContext context, UIPropertySheet propertySheet, PropertySheetItem item) { - - this.node = propertySheet.getNode(); - - return super.createComponent(context, propertySheet, item); - } - - @Override - protected void setupConverter(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem property, - PropertyDefinition propertyDef, UIComponent component) - { - createAndSetConverter(context, LanguageConverter.CONVERTER_ID, component); - } - - @Override - protected void setupMandatoryValidation(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem item, - UIComponent component, boolean realTimeChecking, String idSuffix) - { - // null is may be a right value for a language - } - - /** - * Set the injected userPreferencesBean - * - * @param userPreferencesBean - */ - public void setUserPreferencesBean(UserPreferencesBean userPreferencesBean) - { - this.userPreferencesBean = userPreferencesBean; - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/bean/generator/LinkGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/LinkGenerator.java deleted file mode 100644 index 7cf0f08217..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/LinkGenerator.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import javax.faces.component.UIComponent; -import javax.faces.component.UIOutput; -import javax.faces.context.FacesContext; - -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.ui.common.ComponentConstants; -import org.alfresco.web.ui.repo.component.property.PropertySheetItem; -import org.alfresco.web.ui.repo.component.property.UIPropertySheet; - -/** - * Link Generator. - * - * Generates a link tag which opend the URL into a new browsers window. - * - * @author Roy Wetherall - */ -public class LinkGenerator extends BaseComponentGenerator -{ - private boolean inEditMode = false; - - /** - * @see org.alfresco.web.bean.generator.IComponentGenerator#generate(javax.faces.context.FacesContext, java.lang.String) - */ - @SuppressWarnings("unchecked") - public UIComponent generate(FacesContext context, String id) - { - UIComponent component = null; - if (this.inEditMode == false) - { - component = context.getApplication().createComponent(UIOutput.COMPONENT_TYPE); - component.setRendererType("javax.faces.Link"); - component.getAttributes().put("target", "new"); - } - else - { - component = context.getApplication().createComponent(ComponentConstants.JAVAX_FACES_INPUT); - component.setRendererType(ComponentConstants.JAVAX_FACES_TEXT); - } - - FacesHelper.setupComponentId(context, component, id); - return component; - } - - /** - * @see org.alfresco.web.bean.generator.BaseComponentGenerator#createComponent(javax.faces.context.FacesContext, org.alfresco.web.ui.repo.component.property.UIPropertySheet, org.alfresco.web.ui.repo.component.property.PropertySheetItem) - */ - @Override - protected UIComponent createComponent(FacesContext context, UIPropertySheet propertySheet, PropertySheetItem item) - { - this.inEditMode = propertySheet.inEditMode(); - return this.generate(context, item.getName()); - } - - /** - * @see org.alfresco.web.bean.generator.BaseComponentGenerator#setupProperty(javax.faces.context.FacesContext, org.alfresco.web.ui.repo.component.property.UIPropertySheet, org.alfresco.web.ui.repo.component.property.PropertySheetItem, org.alfresco.service.cmr.dictionary.PropertyDefinition, javax.faces.component.UIComponent) - */ - @SuppressWarnings("unchecked") - @Override - protected void setupProperty(FacesContext context, UIPropertySheet propertySheet, - PropertySheetItem item, PropertyDefinition propertyDef, UIComponent component) - { - super.setupProperty(context, propertySheet, item, propertyDef, component); - - if (component.getRendererType().equals("javax.faces.Link") == true) - { - // Add child text component - UIOutput output = createOutputTextComponent(context, "linklabel_" + component.getId()); - output.setValueBinding("value", component.getValueBinding("value")); - component.getChildren().add(output); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/generator/MimeTypeSelectorGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/MimeTypeSelectorGenerator.java deleted file mode 100644 index b58cfe91a9..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/MimeTypeSelectorGenerator.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; - -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.ui.repo.component.UIMimeTypeSelector; -import org.alfresco.web.ui.repo.component.property.PropertySheetItem; -import org.alfresco.web.ui.repo.component.property.UIPropertySheet; -import org.alfresco.web.ui.repo.converter.MimeTypeConverter; - -/** - * Generates a MIME type selector component. - * - * @author gavinc - */ -public class MimeTypeSelectorGenerator extends BaseComponentGenerator -{ - public UIComponent generate(FacesContext context, String id) - { - UIComponent component = context.getApplication(). - createComponent(UIMimeTypeSelector.COMPONENT_TYPE); - FacesHelper.setupComponentId(context, component, id); - - return component; - } - - @Override - protected void setupConverter(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem property, - PropertyDefinition propertyDef, UIComponent component) - { - if (propertySheet.inEditMode() == false) - { - if (property.getConverter() != null) - { - // create and add the custom converter - createAndSetConverter(context, property.getConverter(), component); - } - else - { - // if there isn't a custom converter add the mime type - // converter as a default - createAndSetConverter(context, MimeTypeConverter.CONVERTER_ID, - component); - } - } - } - - @Override - protected void setupMandatoryValidation(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem item, - UIComponent component, boolean realTimeChecking, String idSuffix) - { - // a mime type selector will always have one value or another - // so there is no need to create a mandatory validation rule. - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/generator/MlContainerLanguageSelectorGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/MlContainerLanguageSelectorGenerator.java deleted file mode 100644 index 4b55f60a58..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/MlContainerLanguageSelectorGenerator.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.faces.model.SelectItem; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.ml.ContentFilterLanguagesService; -import org.alfresco.service.cmr.ml.MultilingualContentService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; - - -/** - * Generates a LANGUAGE selector component for display a list of language - * for a ML container. - * - * The list of languages must contains the languages of each of this non-empty - * translations. - * - * @author Yannick Pignot - */ -public class MlContainerLanguageSelectorGenerator extends LanguageSelectorGenerator -{ - protected MultilingualContentService multilingualContentService; - protected ContentFilterLanguagesService contentFilterLanguagesService; - protected NodeService nodeService; - - protected SelectItem[] getLanguageItems() - { - Map translations = multilingualContentService.getTranslations(node.getNodeRef()); - - List items = new ArrayList(); - - for(Map.Entry entry : translations.entrySet()) - { - if(!nodeService.hasAspect(entry.getValue(), ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION)) - { - Locale loc = entry.getKey(); - - items.add(new SelectItem( - loc.getLanguage(), - contentFilterLanguagesService.getLabelByCode(loc.toString()))); - - } - } - - SelectItem[] itemsArray = new SelectItem[items.size()]; - items.toArray(itemsArray); - - return itemsArray; - } - - /** - * Set the injected contentFilterLanguagesService - * - * @param contentFilterLanguagesService - */ - public void setContentFilterLanguagesService( - ContentFilterLanguagesService contentFilterLanguagesService) - { - this.contentFilterLanguagesService = contentFilterLanguagesService; - } - - /** - * Set the injected multilingualContentService - * - * @param multilingualContentService - */ - public void setMultilingualContentService( - MultilingualContentService multilingualContentService) - { - this.multilingualContentService = multilingualContentService; - } - - /** - * Set the injected nodeService - * - * @param nodeService the nodeService to set - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/bean/generator/MultilingualTextAreaGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/MultilingualTextAreaGenerator.java deleted file mode 100644 index 16690bafec..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/MultilingualTextAreaGenerator.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import javax.faces.component.UIComponent; -import javax.faces.component.UIInput; -import javax.faces.component.UIOutput; -import javax.faces.component.UISelectOne; -import javax.faces.context.FacesContext; - -import org.alfresco.web.ui.repo.RepoConstants; -import org.alfresco.web.ui.repo.component.property.PropertySheetItem; -import org.alfresco.web.ui.repo.component.property.UIPropertySheet; - -/** - * Generates a multilingual text area component. - * - * @author gavinc - */ -public class MultilingualTextAreaGenerator extends TextAreaGenerator -{ - @Override - public UIComponent generateAndAdd(FacesContext context, UIPropertySheet propertySheet, - PropertySheetItem item) - { - UIComponent component = super.generateAndAdd(context, propertySheet, item); - - if ((component instanceof UIInput) && (component instanceof UISelectOne) == false) - { - component.setRendererType(RepoConstants.ALFRESCO_FACES_MLTEXTAREA_RENDERER); - } - else if ((component instanceof UIOutput)) - { - component.setRendererType(RepoConstants.ALFRESCO_FACES_MLTEXT_RENDERER); - } - - return component; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/generator/MultilingualTextFieldGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/MultilingualTextFieldGenerator.java deleted file mode 100644 index d0107ca320..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/MultilingualTextFieldGenerator.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import javax.faces.component.UIComponent; -import javax.faces.component.UISelectOne; -import javax.faces.context.FacesContext; - -import org.alfresco.web.ui.repo.RepoConstants; -import org.alfresco.web.ui.repo.component.UIMultiValueEditor; -import org.alfresco.web.ui.repo.component.property.PropertySheetItem; -import org.alfresco.web.ui.repo.component.property.UIPropertySheet; - -/** - * Generates a multilingual text field component. - * - * @author gavinc - */ -public class MultilingualTextFieldGenerator extends TextFieldGenerator -{ - @Override - public UIComponent generateAndAdd(FacesContext context, UIPropertySheet propertySheet, - PropertySheetItem item) - { - UIComponent component = super.generateAndAdd(context, propertySheet, item); - - if ((component instanceof UISelectOne) == false && - (component instanceof UIMultiValueEditor) == false) - { - component.setRendererType(RepoConstants.ALFRESCO_FACES_MLTEXT_RENDERER); - } - - return component; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/generator/SeparatorGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/SeparatorGenerator.java deleted file mode 100644 index 1fe2ec1f9c..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/SeparatorGenerator.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -/** - * Generates a component to represent a separator using the HTML <hr/> element. - * - * @author gavinc - */ -public class SeparatorGenerator extends HtmlSeparatorGenerator -{ - public SeparatorGenerator() - { - // For the standard separator just show a


element - - this.html = "

"; - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/bean/generator/SpaceIconPickerGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/SpaceIconPickerGenerator.java deleted file mode 100644 index 7e037c5ffe..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/SpaceIconPickerGenerator.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.el.ValueBinding; - -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.ui.common.component.UIListItems; -import org.alfresco.web.ui.repo.RepoConstants; -import org.alfresco.web.ui.repo.component.property.PropertySheetItem; -import org.alfresco.web.ui.repo.component.property.UIPropertySheet; - -/** - * Generates the image picker component with rounded corners for selecting - * an icon for a space. - * - * @author gavinc - */ -public class SpaceIconPickerGenerator extends BaseComponentGenerator -{ - @SuppressWarnings("unchecked") - public UIComponent generate(FacesContext context, String id) - { - // create the outer component - UIComponent component = context.getApplication(). - createComponent(RepoConstants.ALFRESCO_FACES_IMAGE_PICKER); - - // setup the outer component - component.setRendererType(RepoConstants.ALFRESCO_FACES_RADIO_PANEL_RENDERER); - FacesHelper.setupComponentId(context, component, id); - component.getAttributes().put("columns", new Integer(6)); - component.getAttributes().put("spacing", new Integer(4)); - component.getAttributes().put("panelBorder", "blue"); - component.getAttributes().put("panelBgcolor", "#D3E6FE"); - - return component; - } - - @Override - @SuppressWarnings("unchecked") - protected void setupProperty(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem item, - PropertyDefinition propertyDef, UIComponent component) - { - // do the standard setup - super.setupProperty(context, propertySheet, item, propertyDef, component); - - // if the property sheet is in edit mode we also need to setup the - // list of icons the user can select from - if (propertySheet.inEditMode()) - { - // create the list items child component - UIListItems items = (UIListItems)context.getApplication(). - createComponent(RepoConstants.ALFRESCO_FACES_LIST_ITEMS); - - // setup the value binding for the list of icons, this needs - // to be sensitive to the bean used for the property sheet - // we therefore need to get the value binding expression and - // extract the bean name and then add '.icons' to the end, - // this means any page that uses this component must supply - // a getIcons method that returns a List of UIListItem's - ValueBinding binding = propertySheet.getValueBinding("value"); - String expression = binding.getExpressionString(); - String beanName = expression.substring(2, expression.indexOf(".")+1); - if (beanName.equals("DialogManager.") || beanName.equals("WizardManager.")) - { - // deal with the special dialog and wizard manager beans by - // adding .bean - beanName = beanName + "bean."; - } - String newExpression = "#{" + beanName + "icons}"; - - ValueBinding vb = context.getApplication().createValueBinding(newExpression); - items.setValueBinding("value", vb); - - // add the list items component to the image picker component - component.getChildren().add(items); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/generator/StoreSelectorGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/StoreSelectorGenerator.java deleted file mode 100644 index d07a6311c8..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/StoreSelectorGenerator.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.ui.repo.component.UIStoreSelector; - -/** - * Generates a content store selector component. - */ -public class StoreSelectorGenerator extends BaseComponentGenerator -{ - public UIComponent generate(FacesContext context, String id) - { - UIComponent component = context.getApplication(). - createComponent(UIStoreSelector.COMPONENT_TYPE); - FacesHelper.setupComponentId(context, component, id); - - return component; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/generator/TextAreaGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/TextAreaGenerator.java deleted file mode 100644 index f11b3861b8..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/TextAreaGenerator.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.ui.common.ComponentConstants; - -/** - * Generates a text field component. - * - * @author gavinc - */ -public class TextAreaGenerator extends TextFieldGenerator -{ - private int rows = 3; - private int columns = 32; - - /** - * @return Returns the number of columns - */ - public int getColumns() - { - return columns; - } - - /** - * @param columns Sets the number of columns - */ - public void setColumns(int columns) - { - this.columns = columns; - } - - /** - * @return Returns the number of rows - */ - public int getRows() - { - return rows; - } - - /** - * @param rows Sets the number of rows - */ - public void setRows(int rows) - { - this.rows = rows; - } - - @SuppressWarnings("unchecked") - public UIComponent generate(FacesContext context, String id) - { - UIComponent component = context.getApplication(). - createComponent(ComponentConstants.JAVAX_FACES_INPUT); - component.setRendererType(ComponentConstants.JAVAX_FACES_TEXTAREA); - FacesHelper.setupComponentId(context, component, id); - - component.getAttributes().put("rows", this.rows); - component.getAttributes().put("cols", this.columns); - - // MNT-10171 Exception thrown if Share metadata is longer than 1024 characters - if (ContentModel.PROP_DESCRIPTION.getLocalName().equals(id)) - { - // add 'onfocus' event for adding 'maxlength' attribute - component.getAttributes().put("onfocus", "addMaxLengthForDescriptionTextArea(this)"); - } - - return component; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/generator/TextFieldGenerator.java b/war/src/main/java/org/alfresco/web/bean/generator/TextFieldGenerator.java deleted file mode 100644 index cfc081fc50..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/generator/TextFieldGenerator.java +++ /dev/null @@ -1,359 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.generator; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.List; - -import javax.faces.component.UIComponent; -import javax.faces.component.UIOutput; -import javax.faces.component.UISelectItems; -import javax.faces.component.UISelectOne; -import javax.faces.context.FacesContext; -import javax.faces.convert.Converter; -import javax.faces.convert.FloatConverter; -import javax.faces.convert.IntegerConverter; -import javax.faces.convert.LongConverter; -import javax.faces.model.SelectItem; - -import org.alfresco.repo.dictionary.constraint.ListOfValuesConstraint; -import org.alfresco.service.cmr.dictionary.Constraint; -import org.alfresco.service.cmr.dictionary.ConstraintDefinition; -import org.alfresco.service.cmr.dictionary.DataTypeDefinition; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.ui.common.ComponentConstants; -import org.alfresco.web.ui.repo.component.UIMultiValueEditor; -import org.alfresco.web.ui.repo.component.property.PropertySheetItem; -import org.alfresco.web.ui.repo.component.property.UIPropertySheet; -import org.alfresco.web.ui.repo.component.property.UIPropertySheet.ClientValidation; - -/** - * Generates a text field component. - * - * @author gavinc - */ -public class TextFieldGenerator extends BaseComponentGenerator -{ - private int size = 35; - private int maxLength = 1024; - - /** - * @return Returns the default size for a text field - */ - public int getSize() - { - return size; - } - - /** - * @param size Sets the size of a text field - */ - public void setSize(int size) - { - this.size = size; - } - - /** - * @return Returns the max length for the text field - */ - public int getMaxLength() - { - return maxLength; - } - - /** - * @param maxLength Sets the max length of the text field - */ - public void setMaxLength(int maxLength) - { - this.maxLength = maxLength; - } - - @SuppressWarnings("unchecked") - public UIComponent generate(FacesContext context, String id) - { - UIComponent component = context.getApplication(). - createComponent(ComponentConstants.JAVAX_FACES_INPUT); - component.setRendererType(ComponentConstants.JAVAX_FACES_TEXT); - FacesHelper.setupComponentId(context, component, id); - - component.getAttributes().put("size", this.size); - component.getAttributes().put("maxlength", this.maxLength); - - return component; - } - - @Override - @SuppressWarnings("unchecked") - protected UIComponent createComponent(FacesContext context, UIPropertySheet propertySheet, - PropertySheetItem item) - { - UIComponent component = null; - - if (propertySheet.inEditMode()) - { - // if the field has the list of values constraint - // and it is editable a SelectOne component is - // required otherwise create the standard edit component - ListOfValuesConstraint constraint = getListOfValuesConstraint( - context, propertySheet, item); - - PropertyDefinition propDef = this.getPropertyDefinition(context, - propertySheet.getNode(), item.getName()); - - if (constraint != null && item.isReadOnly() == false && - propDef != null && propDef.isProtected() == false) - { - component = context.getApplication().createComponent( - UISelectOne.COMPONENT_TYPE); - FacesHelper.setupComponentId(context, component, item.getName()); - - // create the list of choices - UISelectItems itemsComponent = (UISelectItems)context.getApplication(). - createComponent("javax.faces.SelectItems"); - - List values = constraint.getAllowedValues(); - List items = new ArrayList(values.size()); - for (String value : values) - { - Object obj = null; - - // we need to setup the list with objects of the correct type - if (propDef.getDataType().getName().equals(DataTypeDefinition.INT)) - { - obj = Integer.valueOf(value); - } - else if (propDef.getDataType().getName().equals(DataTypeDefinition.LONG)) - { - obj = Long.valueOf(value); - } - else if (propDef.getDataType().getName().equals(DataTypeDefinition.DOUBLE)) - { - obj = Double.valueOf(value); - } - else if (propDef.getDataType().getName().equals(DataTypeDefinition.FLOAT)) - { - obj = Float.valueOf(value); - } - else - { - obj = value; - } - - // retrieve the display label - String label = constraint.getDisplayLabel(value, dataDictionary.getDictionaryService()); - if (label == null) - { - label = value; - } - - items.add(new SelectItem(obj, label)); - } - - itemsComponent.setValue(items); - - // add the items as a child component - component.getChildren().add(itemsComponent); - } - else - { - // use the standard component in edit mode - component = generate(context, item.getName()); - } - } - else - { - // create an output text component in view mode - component = createOutputTextComponent(context, item.getName()); - } - - return component; - } - - @Override - @SuppressWarnings("unchecked") - protected void setupMandatoryValidation(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem item, - UIComponent component, boolean realTimeChecking, - String idSuffix) - { - if (component instanceof UIMultiValueEditor) - { - // Override the setup of the mandatory validation - // so we can send the _current_value id suffix. - // We also enable real time so the page load - // check disables the ok button if necessary, as the user - // adds or removes items from the multi value list the - // page will be refreshed and therefore re-check the status. - - super.setupMandatoryValidation(context, propertySheet, item, - component, true, "_current_value"); - } - else if (component instanceof UISelectOne) - { - // when there is a list of values constraint there - // will always be a value so validation is not required. - } - else - { - // setup the client validation rule with real time validation enabled - super.setupMandatoryValidation(context, propertySheet, item, - component, true, idSuffix); - - // add event handler to kick off real time checks - component.getAttributes().put("onkeyup", "processButtonState();"); - } - } - - @Override - @SuppressWarnings("unchecked") - protected void setupConstraints(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem property, - PropertyDefinition propertyDef, UIComponent component) - { - // do the default processing first - super.setupConstraints(context, propertySheet, property, - propertyDef, component); - - // if the property type is a number based type and the property - // sheet is in edit mode and validation is turned, on add the - // validateIsNumber validation function - if (propertySheet.inEditMode() && propertySheet.isValidationEnabled() && - propertyDef != null) - { - // check the type of the property is a number - if (propertyDef.getDataType().getName().equals(DataTypeDefinition.DOUBLE) || - propertyDef.getDataType().getName().equals(DataTypeDefinition.FLOAT) || - propertyDef.getDataType().getName().equals(DataTypeDefinition.INT) || - propertyDef.getDataType().getName().equals(DataTypeDefinition.LONG)) - { - List params = new ArrayList(3); - - // add the value parameter - String value = "document.getElementById('" + - component.getClientId(context) + "')"; - params.add(value); - - // add the validation failed message to show - String msg = Application.getMessage(context, "validation_is_number"); - addStringConstraintParam(params, - MessageFormat.format(msg, new Object[] {property.getResolvedDisplayLabel()})); - - // add the validation case to the property sheet - propertySheet.addClientValidation(new ClientValidation("validateIsNumber", - params, false)); - } - } - } - - /** - * Retrieves the list of values constraint for the item, if it has one - * - * @param context FacesContext - * @param propertySheet The property sheet being generated - * @param item The item being generated - * @return The constraint if the item has one, null otherwise - */ - protected ListOfValuesConstraint getListOfValuesConstraint(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem item) - { - ListOfValuesConstraint lovConstraint = null; - - // get the property definition for the item - PropertyDefinition propertyDef = getPropertyDefinition(context, - propertySheet.getNode(), item.getName()); - - if (propertyDef != null) - { - // go through the constaints and see if it has the - // list of values constraint - List constraints = propertyDef.getConstraints(); - for (ConstraintDefinition constraintDef : constraints) - { - Constraint constraint = constraintDef.getConstraint(); - - if (constraint instanceof ListOfValuesConstraint) - { - lovConstraint = (ListOfValuesConstraint)constraint; - break; - } - } - } - - return lovConstraint; - } - - protected void setupConverter(FacesContext context, - UIPropertySheet propertySheet, PropertySheetItem property, - PropertyDefinition propertyDef, UIComponent component) - { - // do default processing - super.setupConverter(context, propertySheet, property, propertyDef, component); - - // if there isn't a converter and the property has a list of values constraint - // on a number property we need to add the appropriate one. - if (propertySheet.inEditMode() && propertyDef != null && - component instanceof UIOutput) - { - Converter converter = ((UIOutput)component).getConverter(); - if (converter == null) - { - ListOfValuesConstraint constraint = getListOfValuesConstraint(context, - propertySheet, property); - if (constraint != null) - { - String converterId = null; - - if (propertyDef.getDataType().getName().equals(DataTypeDefinition.INT)) - { - converterId = IntegerConverter.CONVERTER_ID; - } - else if (propertyDef.getDataType().getName().equals(DataTypeDefinition.LONG)) - { - converterId = LongConverter.CONVERTER_ID; - } - else if (propertyDef.getDataType().getName().equals(DataTypeDefinition.DOUBLE)) - { - // NOTE: the constant for the double converter is wrong in MyFaces!! - converterId = "javax.faces.Double"; - } - else if (propertyDef.getDataType().getName().equals(DataTypeDefinition.FLOAT)) - { - converterId = FloatConverter.CONVERTER_ID; - } - - if (converterId != null) - { - createAndSetConverter(context, converterId, component); - } - } - } - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/groups/AddUsersDialog.java b/war/src/main/java/org/alfresco/web/bean/groups/AddUsersDialog.java deleted file mode 100644 index 9ca47f2ac6..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/groups/AddUsersDialog.java +++ /dev/null @@ -1,342 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.groups; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.faces.model.DataModel; -import javax.faces.model.ListDataModel; -import javax.faces.model.SelectItem; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ContentModel; -import org.alfresco.query.PagingRequest; -import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.repo.transaction.RetryingTransactionHelper; -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.security.AuthorityService; -import org.alfresco.service.cmr.security.PersonService; -import org.alfresco.service.cmr.security.PersonService.PersonInfo; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.groups.GroupsDialog.UserAuthorityDetails; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.SortableSelectItem; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIGenericPicker; -import org.apache.lucene.search.BooleanQuery; - -/** - * Implementation of the add user dialog. - * - * @author YanO - * @author gavinc - */ -public class AddUsersDialog extends BaseDialogBean -{ - private static final long serialVersionUID = 4893334797091942357L; - - /** The id of the group to add users to */ - protected String group; - - /** Name of the group to add users to */ - protected String groupName; - - /** The AuthorityService to be used by the bean */ - transient private AuthorityService authService; - - /** personService bean reference */ - transient private PersonService personService; - - /** selected users to be added to a group */ - protected List usersForGroup; - - /** datamodel for table of users added to group */ - transient protected DataModel usersDataModel = null; - - // ------------------------------------------------------------------------------ - // Dialog implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - // retrieve parameters - this.group = parameters.get(GroupsDialog.PARAM_GROUP); - this.groupName = parameters.get(GroupsDialog.PARAM_GROUP_NAME); - - this.usersDataModel = null; - usersForGroup = new ArrayList(); - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - // add each selected user to the current group in turn - Set containedAuthorities = getAuthService().getContainedAuthorities(null, this.group, true); - for (UserAuthorityDetails wrapper : this.usersForGroup) - { - String user = wrapper.getAuthority(); - if (!containedAuthorities.contains(user)) - { - this.getAuthService().addAuthority(this.group, user); - } - } - - return outcome; - } - - @Override - public String getContainerSubTitle() - { - return this.groupName; - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - // ------------------------------------------------------------------------------ - // Bean property getters and setters - - public void setAuthService(AuthorityService authService) - { - this.authService = authService; - } - - /** - * @return the authService - */ - protected AuthorityService getAuthService() - { - //check for null in cluster environment - if (authService == null) - { - authService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getAuthorityService(); - } - return authService; - } - - public void setPersonService(PersonService personService) - { - this.personService = personService; - } - - /** - * @return the personService - */ - protected PersonService getPersonService() - { - //check for null in cluster environment - if (personService == null) - { - personService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPersonService(); - } - return personService; - } - - /** - * @return Returns the usersDataModel. - */ - public DataModel getUsersDataModel() - { - if (this.usersDataModel == null) - { - this.usersDataModel = new ListDataModel(); - } - - // only set the wrapped data once otherwise the rowindex is reset - if (this.usersDataModel.getWrappedData() == null) - { - this.usersDataModel.setWrappedData(this.usersForGroup); - } - - return this.usersDataModel; - } - - // ------------------------------------------------------------------------------ - // Helpers - - /** - * Query callback method executed by the Generic Picker component. This - * method is part of the contract to the Generic Picker, it is up to the - * backing bean to execute whatever query is appropriate and return the - * results. - * - * @param filterIndex Index of the filter drop-down selection - * @param contains Text from the contains textbox - * @return An array of SelectItem objects containing the results to display - * in the picker. - */ - public SelectItem[] pickerCallback(int filterIndex, final String contains) - { - final FacesContext context = FacesContext.getCurrentInstance(); - - UserTransaction tx = null; - try - { - RetryingTransactionHelper txHelper = Repository.getRetryingTransactionHelper(context);// getUserTransaction(context); - return txHelper.doInTransaction(new RetryingTransactionCallback() - { - public SelectItem[] execute() throws Exception - { - SelectItem[] items = new SelectItem[0]; - - // Use the Person Service to retrieve user details - String term = contains.trim(); - if (term.length() != 0) - { - List persons = getPersonService().getPeople( - Utils.generatePersonFilter(contains.trim()), - true, - Utils.generatePersonSort(), - new PagingRequest(Utils.getPersonMaxResults(), null) - ).getPage(); - - ArrayList itemList = new ArrayList(persons.size()); - for (PersonInfo person : persons) - { - String username = person.getUserName(); - if (AuthenticationUtil.getGuestUserName().equals(username) == false) - { - String firstName = person.getFirstName(); - String lastName = person.getLastName(); - - // build a sensible label for display - String name = (firstName != null ? firstName : "") + ' ' + (lastName != null ? lastName : ""); - SelectItem item = new SortableSelectItem(username, name + " [" + username + "]", lastName != null ? lastName : username); - itemList.add(item); - } - } - items = new SelectItem[itemList.size()]; - itemList.toArray(items); - } - return items; - } - }); - } - catch (BooleanQuery.TooManyClauses clauses) - { - Utils.addErrorMessage(Application.getMessage( - FacesContext.getCurrentInstance(), "too_many_users")); - - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - - return new SelectItem[0]; - } - catch (Exception err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err); - try - { - if (tx != null) - { - tx.rollback(); - } - } - catch (Exception tex) - { - } - return new SelectItem[0]; - } - } - - // ------------------------------------------------------------------------------ - // Event handlers - - /** - * Add the selected User to the list for adding to a Group - */ - public void addSelectedUsers(ActionEvent event) - { - UIGenericPicker picker = (UIGenericPicker) event.getComponent().findComponent("picker"); - String[] results = picker.getSelectedResults(); - if (results != null) - { - for (int i = 0; i < results.length; i++) - { - String authority = results[i]; - - // check for same authority so not added twice - boolean foundExisting = false; - for (int n = 0; n < this.usersForGroup.size(); n++) - { - UserAuthorityDetails wrapper = this.usersForGroup.get(n); - if (authority.equals(wrapper.getAuthority())) - { - foundExisting = true; - break; - } - } - - if (foundExisting == false) - { - StringBuilder label = new StringBuilder(48); - - // build a display label showing the user person name - if (this.getPersonService().personExists(authority) == true) - { - // found a Person with a User authority - NodeRef ref = this.getPersonService().getPerson(authority); - String firstName = (String)getNodeService().getProperty(ref, ContentModel.PROP_FIRSTNAME); - String lastName = (String)getNodeService().getProperty(ref, ContentModel.PROP_LASTNAME); - - // build a sensible label for display - label.append(firstName != null ? firstName : "").append(' ').append(lastName != null ? lastName : ""); - - // add a wrapper object with the details to the results list for display - UserAuthorityDetails userDetails = new UserAuthorityDetails(label.toString(), authority); - this.usersForGroup.add(userDetails); - } - } - } - } - } - - /** - * Action handler called when the Remove button is pressed to remove a user - * from the results list - */ - public void removeUserSelection(ActionEvent event) - { - UserAuthorityDetails wrapper = (UserAuthorityDetails) this.usersDataModel.getRowData(); - if (wrapper != null) - { - this.usersForGroup.remove(wrapper); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/groups/CreateGroupDialog.java b/war/src/main/java/org/alfresco/web/bean/groups/CreateGroupDialog.java deleted file mode 100644 index 7d07bce007..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/groups/CreateGroupDialog.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.groups; - -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.application.FacesMessage; -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.validator.ValidatorException; - -import org.alfresco.service.cmr.security.AuthorityService; -import org.alfresco.service.cmr.security.AuthorityType; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.Utils; - -public class CreateGroupDialog extends BaseDialogBean -{ - private static final long serialVersionUID = -8074475974375860695L; - - protected String parentGroup; - protected String parentGroupName; - protected String name; - - /** The AuthorityService to be used by the bean */ - transient private AuthorityService authService; - - private static final String MSG_ERR_EXISTS = "groups_err_exists"; - private static final String MSG_GROUPNAME_LENGTH = "groups_err_group_name_length"; - private static final String MSG_ERR_NAME = "groups_err_group_name"; - private static final String MSG_ROOT_GROUPS = "root_groups"; - private static final String MSG_BUTTON_NEW_GROUP = "new_group"; - - - // ------------------------------------------------------------------------------ - // Dialog implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - // retrieve parameters - this.parentGroup = parameters.get(GroupsDialog.PARAM_GROUP); - this.parentGroupName = parameters.get(GroupsDialog.PARAM_GROUP_NAME); - - // reset variables - this.name = null; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - // create new Group using Authentication Service - String groupName = this.getAuthService().getName(AuthorityType.GROUP, this.name); - if (this.getAuthService().authorityExists(groupName) == false) - { - this.getAuthService().createAuthority(AuthorityType.GROUP, this.name); - if (this.parentGroup != null) - { - this.getAuthService().addAuthority(this.parentGroup, groupName); - } - } - else - { - Utils.addErrorMessage(Application.getMessage(context, MSG_ERR_EXISTS)); - outcome = null; - this.isFinished = false; - } - - return outcome; - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_BUTTON_NEW_GROUP); - } - - @Override - public String getContainerSubTitle() - { - String subtitle = null; - - if (this.parentGroupName != null) - { - subtitle = this.parentGroupName; - } - else - { - subtitle = Application.getMessage(FacesContext.getCurrentInstance(), MSG_ROOT_GROUPS); - } - - return subtitle; - } - - - // ------------------------------------------------------------------------------ - // Bean property getters and setters - - public String getName() - { - return this.name; - } - - public void setName(String name) - { - this.name = name; - } - - public void setAuthService(AuthorityService authService) - { - this.authService = authService; - } - - /** - * @return the authService - */ - protected AuthorityService getAuthService() - { - if (authService == null) - { - authService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getAuthorityService(); - } - return authService; - } - - - // ------------------------------------------------------------------------------ - // Helpers - - public void validateGroupName(FacesContext context, UIComponent component, Object value) throws ValidatorException - { - int minGroupNameLength = Application.getClientConfig(context).getMinGroupNameLength(); - - String name = ((String)value).trim(); - - if (name.length() < minGroupNameLength || name.length() > 100) - { - String err = MessageFormat.format(Application.getMessage(context, MSG_GROUPNAME_LENGTH), - new Object[]{minGroupNameLength, 100}); - throw new ValidatorException(new FacesMessage(err)); - } - - if (name.indexOf('"') != -1 || name.indexOf('\\') != -1) - { - String err = MessageFormat.format(Application.getMessage(context, MSG_ERR_NAME), - new Object[] { "\", \\" }); - throw new ValidatorException(new FacesMessage(err)); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/groups/DeleteGroupDialog.java b/war/src/main/java/org/alfresco/web/bean/groups/DeleteGroupDialog.java deleted file mode 100644 index 9d71903dcc..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/groups/DeleteGroupDialog.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.groups; - -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.service.cmr.security.AuthorityService; -import org.alfresco.service.cmr.security.AuthorityType; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Repository; - -public class DeleteGroupDialog extends BaseDialogBean -{ - private static final long serialVersionUID = -8743700617152460027L; - - /** The group to be deleted */ - protected String group = null; - protected String groupName = null; - - /** The number of items the group contains */ - protected int numItemsInGroup = 0; - - /** The AuthorityService to be used by the bean */ - transient private AuthorityService authService; - - private static final String MSG_DELETE = "delete"; - private static final String MSG_DELETE_GROUP = "delete_group"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - // ------------------------------------------------------------------------------ - // Dialog implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - // retrieve parameters - this.group = parameters.get(GroupsDialog.PARAM_GROUP); - this.groupName = parameters.get(GroupsDialog.PARAM_GROUP_NAME); - - // calculate the number of items the givev group has - if (this.group != null) - { - numItemsInGroup = this.getAuthService().getContainedAuthorities( - AuthorityType.GROUP, this.group, false).size(); - numItemsInGroup += this.getAuthService().getContainedAuthorities( - AuthorityType.USER, this.group, false).size(); - } - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - // delete group using the Authentication Service - this.getAuthService().deleteAuthority(this.group); - - return outcome; - } - - @Override - protected String doPostCommitProcessing(FacesContext context, String outcome) - { - // add the group to the request object so it gets picked up by - // groups dialog, this will allow it to be removed from the breadcrumb - context.getExternalContext().getRequestMap().put( - GroupsDialog.KEY_GROUP, this.group); - - return outcome; - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_DELETE); - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_DELETE_GROUP) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) + - this.groupName + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - // ------------------------------------------------------------------------------ - // Bean property getters and setters - - public String getGroupName() - { - return this.groupName; - } - - public int getNumItemsInGroup() - { - return this.numItemsInGroup; - } - - public void setAuthService(AuthorityService authService) - { - this.authService = authService; - } - - /** - * @return the authService - */ - protected AuthorityService getAuthService() - { - //check for null in cluster environment - if (authService == null) - { - authService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getAuthorityService(); - } - return authService; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/groups/GroupsDialog.java b/war/src/main/java/org/alfresco/web/bean/groups/GroupsDialog.java deleted file mode 100644 index db0c257fed..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/groups/GroupsDialog.java +++ /dev/null @@ -1,847 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.groups; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ContentModel; -import org.alfresco.query.PagingRequest; -import org.alfresco.query.PagingResults; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.security.AuthorityService; -import org.alfresco.service.cmr.security.AuthorityType; -import org.alfresco.service.cmr.security.PersonService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.IContextListener; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.dialog.ChangeViewSupport; -import org.alfresco.web.bean.dialog.FilterViewSupport; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.data.DynamicResolver; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.IBreadcrumbHandler; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.alfresco.web.ui.common.component.UIBreadcrumb; -import org.alfresco.web.ui.common.component.UIListItem; -import org.alfresco.web.ui.common.component.UIModeList; -import org.alfresco.web.ui.common.component.data.UIRichList; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Backing Bean for the Groups Management pages. - * - * @author Kevin Roast - */ -public class GroupsDialog extends BaseDialogBean - implements IContextListener, FilterViewSupport, ChangeViewSupport -{ - private static final long serialVersionUID = -624617545796275734L; - - public static final String KEY_GROUP = "group"; - public static final String PARAM_GROUP = "group"; - public static final String PARAM_GROUP_NAME = "groupName"; - - /** The AuthorityService to be used by the bean */ - transient private AuthorityService authService; - - /** personService bean reference */ - transient private PersonService personService; - - /** Component references */ - protected UIRichList groupsRichList; - protected UIRichList usersRichList; - - /** Groups */ - protected List> groups = Collections.> emptyList(); - - /** Currently visible Group Authority */ - protected String group = null; - protected String groupName = null; - - /** RichList view mode */ - protected String viewMode = VIEW_ICONS; - - /** Filter mode */ - protected String filterMode = FILTER_CHILDREN; - - /** Groups path breadcrumb location */ - protected List location = null; - - private static final String VIEW_ICONS = "icons"; - private static final String VIEW_DETAILS = "details"; - private static final String FILTER_CHILDREN = "children"; - private static final String FILTER_ALL = "all"; - - private static final String LABEL_VIEW_ICONS = "group_icons"; - private static final String LABEL_VIEW_DETAILS = "group_details"; - private static final String LABEL_FILTER_CHILDREN = "group_filter_children"; - private static final String LABEL_FILTER_ALL = "group_filter_all"; - - private static final String MSG_ROOT_GROUPS = "root_groups"; - private static final String MSG_CLOSE = "close"; - - private static Log logger = LogFactory.getLog(GroupsDialog.class); - - /** Groups search criteria */ - private String groupsSearchCriteria = null; - private boolean searchAll = false; - - - // ------------------------------------------------------------------------------ - // Construction - - /** - * Default Constructor - */ - public GroupsDialog() - { - UIContextService.getInstance(FacesContext.getCurrentInstance()).registerBean(this); - } - - // ------------------------------------------------------------------------------ - // Dialog implementation - - - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - @Override - public String cancel() - { - // reset UI back to group search on leaving the groups dialog - this.location = null; - setCurrentGroup(null, null); - - return super.cancel(); - } - - @Override - public String getContainerSubTitle() - { - String subtitle = null; - - if (this.group != null) - { - subtitle = this.groupName; - } - else - { - subtitle = Application.getMessage(FacesContext.getCurrentInstance(), MSG_ROOT_GROUPS); - } - - return subtitle; - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } - - @Override - public void restored() - { - Object groupToRemove = FacesContext.getCurrentInstance().getExternalContext(). - getRequestMap().get(KEY_GROUP); - if (groupToRemove != null) - { - if (logger.isDebugEnabled()) - logger.debug("Removing group '" + groupToRemove + "' from breadcrumb"); - - removeFromBreadcrumb((String)groupToRemove); - } - } - - @Override - public Object getActionsContext() - { - return this; - } - - // ------------------------------------------------------------------------------ - // FilterViewSupport implementation - - public List getFilterItems() - { - FacesContext context = FacesContext.getCurrentInstance(); - List items = new ArrayList(2); - - UIListItem item1 = new UIListItem(); - item1.setValue(FILTER_CHILDREN); - item1.setLabel(Application.getMessage(context, LABEL_FILTER_CHILDREN)); - items.add(item1); - - UIListItem item2 = new UIListItem(); - item2.setValue(FILTER_ALL); - item2.setLabel(Application.getMessage(context, LABEL_FILTER_ALL)); - items.add(item2); - - return items; - } - - public void filterModeChanged(ActionEvent event) - { - UIModeList filterList = (UIModeList)event.getComponent(); - - // update list filter mode from user selection - setFilterMode(filterList.getValue().toString()); - } - - public String getFilterMode() - { - return this.filterMode; - } - - public void setFilterMode(String filterMode) - { - this.filterMode = filterMode; - - // clear datalist cache ready to change results based on filter setting - contextUpdated(); - } - - // ------------------------------------------------------------------------------ - // ChangeViewSupport implementation - - public List getViewItems() - { - FacesContext context = FacesContext.getCurrentInstance(); - List items = new ArrayList(2); - - UIListItem item1 = new UIListItem(); - item1.setValue(VIEW_ICONS); - item1.setLabel(Application.getMessage(context, LABEL_VIEW_ICONS)); - items.add(item1); - - UIListItem item2 = new UIListItem(); - item2.setValue(VIEW_DETAILS); - item2.setLabel(Application.getMessage(context, LABEL_VIEW_DETAILS)); - items.add(item2); - - return items; - } - - public void viewModeChanged(ActionEvent event) - { - UIModeList viewList = (UIModeList)event.getComponent(); - - // update view mode from user selection - setViewMode(viewList.getValue().toString()); - } - - public String getViewMode() - { - return this.viewMode; - } - - public void setViewMode(String viewMode) - { - this.viewMode = viewMode; - } - - // ------------------------------------------------------------------------------ - // Bean property getters and setters - - public String getGroup() - { - return this.group; - } - - public String getGroupName() - { - return this.groupName; - } - - public void setAuthService(AuthorityService authService) - { - this.authService = authService; - } - - private AuthorityService getAuthorityService() - { - if (authService == null) - { - authService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getAuthorityService(); - } - return authService; - } - - public void setPersonService(PersonService personService) - { - this.personService = personService; - } - - private PersonService getPersonService() - { - if (personService == null) - { - personService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPersonService(); - } - return personService; - } - - public UIRichList getGroupsRichList() - { - return groupsRichList; - } - - public void setGroupsRichList(UIRichList groupsRichList) - { - this.groupsRichList = groupsRichList; - } - - public UIRichList getUsersRichList() - { - return usersRichList; - } - - public void setUsersRichList(UIRichList usersRichList) - { - this.usersRichList = usersRichList; - } - - /** - * @return Breadcrumb location list - */ - public List getLocation() - { - if (this.location == null) - { - List loc = new ArrayList(8); - loc.add(new GroupBreadcrumbHandler(null, - Application.getMessage(FacesContext.getCurrentInstance(), MSG_ROOT_GROUPS))); - - this.location = loc; - } - - return this.location; - } - - /** - * @return true if user is in the root group - */ - public boolean isAllowSearchGroups() - { - return (this.group == null); - } - - /** - * @return The list of group objects to display. Returns the list of root groups or the list of sub-groups for the current group if set. - */ - public List> getGroups() - { - displayGroups(); - return this.groups; - } - - /** - * @return Returns the groups search criteria - */ - public String getGroupsSearchCriteria() - { - return this.groupsSearchCriteria; - } - - /** - * Event handler called when the user wishes to search for a group - * - * @return The outcome - */ - public String searchGroups() - { - // clear group context as search is global - this.group = null; - this.searchAll = false; - displayGroups(); - // return null to stay on the same page - return null; - } - - /** - * Action handler to show all the sub-groups in the group - * - * @return The outcome - */ - public String showAllGroups() - { - // clear group context as search is global - this.group = null; - this.searchAll = true; - displayGroups(); - // return null to stay on the same page - return null; - } - - /** - * Searches for groups or lists groups of the current group context - */ - private void displayGroups() - { - // empty the list before we begin the search for a new list - this.groupsRichList.setValue(null); - - List authorities; - if (this.group == null) - { - // Use the search criteria if we are not searching for everything - String search = null; - if (!this.searchAll) - { - if (this.groupsSearchCriteria == null) - { - search = null; - } - else - { - search = groupsSearchCriteria.trim(); - if (search.length() == 0) - { - search = null; - } - else - { - // Let's make it search on the short name/display name prefix - search = search + "*"; - } - } - } - - if (!this.searchAll && search == null) - { - // Do not allow empty searches - this.groups = Collections.> emptyList(); - return; - } - else - { - boolean immediate = (this.filterMode.equals(FILTER_CHILDREN)); - if ((search != null && search.startsWith("*")) || immediate) - { - // if the search term starts with a wildcard or is for immediate children only then use Solr/Lucene based search query to find groups (note: - // results will be eventually consistent if using Solr, rather than embedded Lucene) - Set results = this.authService.findAuthorities(AuthorityType.GROUP, this.group, immediate, search, AuthorityService.ZONE_APP_DEFAULT); - authorities = new ArrayList(results); - } - else - { - // all other searches use the canned query so search results are consistent - PagingResults pagedResults = this.authService.getAuthorities(AuthorityType.GROUP, - AuthorityService.ZONE_APP_DEFAULT, search, true, true, new PagingRequest(10000)); - authorities = pagedResults.getPage(); - } - } - } - else - { - // child groups of the current group - Set results = this.getAuthorityService().getContainedAuthorities(AuthorityType.GROUP, this.group, true); - authorities = new ArrayList(results); - } - - this.groups = new ArrayList>(authorities.size()); - for (String authority : authorities) - { - Map authMap = new HashMap(8); - - String name = this.authService.getAuthorityDisplayName(authority); - if (name == null) - { - name = this.authService.getShortName(name); - } - authMap.put("name", name); - authMap.put("id", authority); - authMap.put("group", authority); - authMap.put("groupName", name); - - this.groups.add(authMap); - } - } - - /** - * @return The list of user objects to display. Returns the list of user for the current group. - */ - public List> getUsers() - { - List> users; - - UserTransaction tx = null; - try - { - FacesContext context = FacesContext.getCurrentInstance(); - tx = Repository.getUserTransaction(context, true); - tx.begin(); - - Set authorities; - if (this.group == null) - { - authorities = Collections.emptySet(); - } - else - { - // users of an existing group - boolean immediate = (this.filterMode.equals(FILTER_CHILDREN)); - authorities = this.getAuthorityService().getContainedAuthorities(AuthorityType.USER, this.group, immediate); - } - users = new ArrayList>(authorities.size()); - for (String authority : authorities) - { - final Map authMap = new HashMap(8); - - final String userName = this.getAuthorityService().getShortName(authority); - authMap.put("userName", userName); - authMap.put("id", Utils.encode(authority)); - authMap.put("name", new AuthorityNamePropertyResolver(userName)); - authMap.put("firstName", new AuthorityPropertyResolver(userName, ContentModel.PROP_FIRSTNAME)); - authMap.put("lastName", new AuthorityPropertyResolver(userName, ContentModel.PROP_LASTNAME)); - - users.add(authMap); - } - - // commit the transaction - tx.commit(); - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err); - users = Collections.>emptyList(); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - - return users; - } - - /** - * Set the current Group Authority. - *

- * Setting this value causes the UI to update and display the specified node as current. - * - * @param group The current group authority. - */ - protected void setCurrentGroup(String group, String groupName) - { - if (logger.isDebugEnabled()) - logger.debug("Setting current group: " + group); - - // set the current Group Authority for our UI context operations - this.group = group; - this.groupName = groupName; - - // reset search context - this.searchAll = false; - - // inform that the UI needs updating after this change - contextUpdated(); - } - - - // ------------------------------------------------------------------------------ - // Action handlers - - /** - * Action called when a Group folder is clicked. - * Navigate into the Group and show child Groups and child Users. - */ - public void clickGroup(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String group = params.get("id"); - if (group != null && group.length() != 0) - { - // refresh UI based on node selection - updateUILocation(group); - setGroupsSearchCriteria(null); - } - } - - /** - * Simple setter - * - * @param groupsSearchCriteria String - */ - public void setGroupsSearchCriteria(String groupsSearchCriteria) - { - this.groupsSearchCriteria = groupsSearchCriteria; - } - - /** - * Remove specified user from the current group - */ - public void removeUser(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String authority = params.get("id"); - if (authority != null && authority.length() != 0) - { - UserTransaction tx = null; - try - { - FacesContext context = FacesContext.getCurrentInstance(); - tx = Repository.getUserTransaction(context); - tx.begin(); - - this.getAuthorityService().removeAuthority(this.group, authority); - - // commit the transaction - tx.commit(); - - // refresh UI after change - contextUpdated(); - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - } - } - - /** - * Update the breadcrumb with the clicked Group location - */ - protected void updateUILocation(String group) - { - String groupName = this.getAuthorityService().getShortName(group); - this.location.add(new GroupBreadcrumbHandler(group, groupName)); - this.setCurrentGroup(group, groupName); - } - - protected void removeFromBreadcrumb(String group) - { - // remove this node from the breadcrumb if required - List location = getLocation(); - GroupBreadcrumbHandler handler = (GroupBreadcrumbHandler) location.get(location.size() - 1); - - // see if the current breadcrumb location is our Group - if (group.equals(handler.Group)) - { - location.remove(location.size() - 1); - - // now work out which Group to set the list to refresh against - if (location.size() != 0) - { - handler = (GroupBreadcrumbHandler) location.get(location.size() - 1); - this.setCurrentGroup(handler.Group, handler.Label); - } - } - } - - - // ------------------------------------------------------------------------------ - // IContextListener implementation - - /** - * @see org.alfresco.web.app.context.IContextListener#contextUpdated() - */ - public void contextUpdated() - { - if (logger.isDebugEnabled()) - logger.debug("Invalidating Group Management Components..."); - - // force a requery of the richlist dataset - if (this.groupsRichList != null) - { - this.groupsRichList.setValue(null); - this.groups = null; - } - - if (this.usersRichList != null) - { - this.usersRichList.setValue(null); - } - } - - /** - * @see org.alfresco.web.app.context.IContextListener#areaChanged() - */ - public void areaChanged() - { - // nothing to do - } - - /** - * @see org.alfresco.web.app.context.IContextListener#spaceChanged() - */ - public void spaceChanged() - { - // nothing to do - } - - - // ------------------------------------------------------------------------------ - // Inner classes - - /** - * Class to handle breadcrumb interaction for Group pages - */ - private class GroupBreadcrumbHandler implements IBreadcrumbHandler - { - private static final long serialVersionUID = 1871876653151036630L; - - /** - * Constructor - * - * @param group The group for this navigation element if any - * @param label Element label - */ - public GroupBreadcrumbHandler(String group, String label) - { - this.Group = group; - this.Label = label; - } - - /** - * @see java.lang.Object#toString() - */ - public String toString() - { - return this.Label; - } - - /** - * @see org.alfresco.web.ui.common.component.IBreadcrumbHandler#navigationOutcome(org.alfresco.web.ui.common.component.UIBreadcrumb) - */ - public String navigationOutcome(UIBreadcrumb breadcrumb) - { - // All group breadcrumb elements relate to a Group - // when selected we set the current Group Id and return - setCurrentGroup(this.Group, this.Label); - location = (List)breadcrumb.getValue(); - - return null; - } - - public String Group; - public String Label; - } - - - /** - * Simple wrapper bean exposing user authority and person details for JSF results list - */ - public static class UserAuthorityDetails implements Serializable - { - private static final long serialVersionUID = 1056255933962068348L; - - public UserAuthorityDetails(String name, String authority) - { - this.name = name; - this.authority = authority; - } - - public String getName() - { - return this.name; - } - - public String getAuthority() - { - return this.authority; - } - - private String name; - private String authority; - } - - - /** - * Simple dynamic resolver class to return authority properties at runtime - */ - public class AuthorityPropertyResolver implements DynamicResolver - { - final private String authority; - final private QName property; - private String value = null; - - AuthorityPropertyResolver(String authority, QName property) - { - this.authority = authority; - this.property = property; - } - - @Override - public String toString() - { - if (this.value == null) - { - NodeRef ref = getPersonService().getPerson(this.authority); - this.value = (String)getNodeService().getProperty(ref, this.property); - } - return this.value; - } - } - - public class AuthorityNamePropertyResolver implements DynamicResolver - { - final private String authority; - private String value = null; - - AuthorityNamePropertyResolver(String authority) - { - this.authority = authority; - } - - @Override - public String toString() - { - if (this.value == null) - { - NodeRef ref = getPersonService().getPerson(this.authority); - String firstName = (String)getNodeService().getProperty(ref, ContentModel.PROP_FIRSTNAME); - String lastName = (String)getNodeService().getProperty(ref, ContentModel.PROP_LASTNAME); - - // build a sensible label for display - StringBuilder label = new StringBuilder(48); - label.append(firstName != null ? firstName : "") - .append(' ') - .append(lastName != null ? lastName : ""); - this.value = label.toString(); - } - return this.value; - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/jmx/JmxDumperBean.java b/war/src/main/java/org/alfresco/web/bean/jmx/JmxDumperBean.java deleted file mode 100644 index 4b9ff8917a..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/jmx/JmxDumperBean.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.jmx; - -import java.io.IOException; -import java.io.PrintWriter; -import java.io.Serializable; -import java.io.StringWriter; - -import javax.faces.context.FacesContext; -import javax.management.MBeanServerConnection; - -import org.alfresco.repo.management.JmxDumpUtil; -import org.alfresco.web.app.servlet.FacesHelper; - -/** - * Backing bean to allow an admin user to dump all JMX Beans and their properties. - */ -public class JmxDumperBean implements Serializable -{ - - private static final long serialVersionUID = -8690237774052781181L; - - // supporting repository services - - /** The MBean server. */ - transient private MBeanServerConnection mbeanServer; - - /** - * Sets the mbean server. - * - * @param mbeanServer - * the mbeanServer to set - */ - public void setMbeanServer(MBeanServerConnection mbeanServer) - { - this.mbeanServer = mbeanServer; - } - - /** - * Gets the mbean server. - * - * @return the mbeanServer - */ - private MBeanServerConnection getMbeanServer() - { - if (this.mbeanServer == null) - { - this.mbeanServer = (MBeanServerConnection) FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), - "alfrescoMBeanServer"); - } - return this.mbeanServer; - } - - /** - * Gets the command result. - * - * @return the result - * @throws IOException - * Signals that an I/O exception has occurred. - */ - public String getResult() throws IOException - { - StringWriter result = new StringWriter(); - PrintWriter out = new PrintWriter(result); - JmxDumpUtil.dumpConnection(getMbeanServer(), out); - out.close(); - return result.toString(); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/ml/AddTranslationDialog.java b/war/src/main/java/org/alfresco/web/bean/ml/AddTranslationDialog.java deleted file mode 100644 index 0157d6996f..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/ml/AddTranslationDialog.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.ml; - -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.model.SelectItem; - -import org.springframework.extensions.surf.util.I18NUtil; -import org.alfresco.service.cmr.ml.MultilingualContentService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.users.UserPreferencesBean; -import org.alfresco.web.bean.content.AddContentDialog; -import org.alfresco.web.bean.repository.Repository; - -/** - * Dialog bean to upload a new document and to add it to an existing MLContainer. - * - * @author yanipig - */ -public class AddTranslationDialog extends AddContentDialog -{ - private static final long serialVersionUID = 5588241907778464543L; - private static final String MSG_OK = "ok"; - - transient private MultilingualContentService multilingualContentService; - private UserPreferencesBean userPreferencesBean; - - // the multilingual container where to add this translation - protected NodeRef mlTranslation; - - // Locale of the new translation - private String language; - - // languages available in the ML container yet - private SelectItem[] unusedLanguages; - - - /* (non-Javadoc) - * @see org.alfresco.web.bean.content.AddContentDialog#init(java.util.Map) - */ - @Override - public void init(Map parameters) - { - super.init(parameters); - - this.language = null; - this.mlTranslation = this.browseBean.getDocument().getNodeRef(); - setFileName(null); - unusedLanguages = null; - } - - /* (non-Javadoc) - * @see org.alfresco.web.bean.content.AddContentDialog#finishImpl(javax.faces.context.FacesContext, java.lang.String) - */ - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - // add the new file to the repository - outcome = super.finishImpl(context, outcome); - - // add a new translation - getMultilingualContentService().addTranslation(this.createdNode, this.mlTranslation, I18NUtil.parseLocale(this.language)); - - return "dialog:close:browse"; - } - - @Override - public String cancel() - { - super.cancel(); - - return getDefaultFinishOutcome(); - } - - public boolean getFinishButtonDisabled() - { - return author == null || author.length() < 1 || language == null; - } - - /** - * @return the locale of this new translation - */ - public String getLanguage() - { - return language; - } - - /** - * @param language the locale of this new translation - */ - public void setLanguage(String language) - { - this.language = language; - } - - /** - * @param unusedLanguages - */ - public void setUnusedLanguages(SelectItem[] unusedLanguages) - { - this.unusedLanguages = unusedLanguages; - } - - /** - * Method calls by the dialog to limit the list of languages. - * - * @return the list of availables translation in the MLContainer - */ - - public SelectItem[] getUnusedLanguages() - { - if(unusedLanguages == null) - { - unusedLanguages = userPreferencesBean.getAvailablesContentFilterLanguages(this.mlTranslation, false); - } - - return unusedLanguages; - } - - public MultilingualContentService getMultilingualContentService() - { - if (multilingualContentService == null) - { - multilingualContentService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getMultilingualContentService(); - } - return multilingualContentService; - } - - public void setMultilingualContentService(MultilingualContentService multilingualContentService) - { - this.multilingualContentService = multilingualContentService; - } - - public UserPreferencesBean getUserPreferencesBean() - { - return userPreferencesBean; - } - - public void setUserPreferencesBean(UserPreferencesBean userPreferencesBean) - { - this.userPreferencesBean = userPreferencesBean; - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_OK); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/ml/AddTranslationWithoutContentDialog.java b/war/src/main/java/org/alfresco/web/bean/ml/AddTranslationWithoutContentDialog.java deleted file mode 100644 index ed36445f03..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/ml/AddTranslationWithoutContentDialog.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.ml; - -import java.util.Locale; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.model.SelectItem; - -import org.springframework.extensions.surf.util.I18NUtil; -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.ml.MultilingualContentService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.users.UserPreferencesBean; - -/** - * Dialog bean to add a new translation without content. I means, a new node is created - * but it doesn't content the propertie {http://www.alfresco.org/model/content/1.0}content - * - * @author Yannick Pignot - */ -public class AddTranslationWithoutContentDialog extends BaseDialogBean -{ - private static final long serialVersionUID = -1252453783397533792L; - - transient private MultilingualContentService multilingualContentService; - private UserPreferencesBean userPreferencesBean; - - // the translation being to be created - protected NodeRef newTranslation; - - private String title; - private String description; - private String author; - private String language; - private boolean showOtherProperties; - - @Override - public void init(Map parameters) - { - super.init(parameters); - - title = null; - description = null; - author = null; - language = null; - showOtherProperties = true; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - // get the reference node - NodeRef refNode = this.browseBean.getDocument().getNodeRef(); - - // get the required properties to create the new node and to make it multilingual - Locale locale = I18NUtil.parseLocale(language); - - // add the empty translation - newTranslation = getMultilingualContentService().addEmptyTranslation(refNode, null, locale); - - // set the properties - getNodeService().setProperty(newTranslation, ContentModel.PROP_DESCRIPTION, description); - getNodeService().setProperty(newTranslation, ContentModel.PROP_AUTHOR, author); - getNodeService().setProperty(newTranslation, ContentModel.PROP_TITLE, title); - - // redirect the user according the value of (show other properties) - if(showOtherProperties) - { - this.browseBean.setDocument(new Node(this.newTranslation)); - return "dialog:setContentProperties"; - } - else - { - return "browse"; - } - } - - /** - * @param userPreferencesBean the userPreferencesBean to set - */ - public void setUserPreferencesBean(UserPreferencesBean userPreferencesBean) - { - this.userPreferencesBean = userPreferencesBean; - } - - /** - * @param multilingualContentService the multilingualContentService to set - */ - public void setMultilingualContentService(MultilingualContentService multilingualContentService) - { - this.multilingualContentService = multilingualContentService; - } - - private MultilingualContentService getMultilingualContentService() - { - if (multilingualContentService == null) - { - multilingualContentService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getMultilingualContentService(); - } - return multilingualContentService; - - } - - /** - * @return the author - */ - public String getAuthor() - { - return author; - } - - /** - * @param author the author to set - */ - public void setAuthor(String author) - { - this.author = author; - } - - /** - * @return the description - */ - public String getDescription() - { - return description; - } - - /** - * @param description the description to set - */ - public void setDescription(String description) - { - this.description = description; - } - - /** - * @return the language - */ - public String getLanguage() - { - return language; - } - - /** - * @param language the language to set - */ - public void setLanguage(String language) - { - this.language = language; - } - - /** - * @return the title - */ - public String getTitle() - { - return title; - } - - /** - * @param title the title to set - */ - public void setTitle(String title) - { - this.title = title; - } - - /** - * @return the unusedLanguages - */ - public SelectItem[] getUnusedLanguages() - { - return userPreferencesBean.getAvailablesContentFilterLanguages(this.browseBean.getDocument().getNodeRef(), false); - } - - /** - * @return the showOtherProperties - */ - public boolean isShowOtherProperties() - { - return showOtherProperties; - } - - /** - * @param showOtherProperties the showOtherProperties to set - */ - public void setShowOtherProperties(boolean showOtherProperties) - { - this.showOtherProperties = showOtherProperties; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/ml/EditMLContainerDialog.java b/war/src/main/java/org/alfresco/web/bean/ml/EditMLContainerDialog.java deleted file mode 100644 index 695204bf25..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/ml/EditMLContainerDialog.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.ml; - -import java.io.Serializable; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.ml.MultilingualContentService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; - -/** - * Dialog bean to edit an existing multilingual container. - * - * @author Yannick Pignot - */ -public class EditMLContainerDialog extends BaseDialogBean -{ - private static final long serialVersionUID = -6340255019962646300L; - - transient private MultilingualContentService multilingualContentService; - - private Node editableNode; - - @Override - public void init(Map parameters) - { - super.init(parameters); - - this.editableNode = initEditableNode(); - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "ok"); - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - // get the container node ref - NodeRef container = editableNode.getNodeRef(); - - // get the modified properties - Map editProperties = this.editableNode.getProperties(); - - // Modify the properties of the container with the user modified properties - // (We don't know which properties have been edited at this point, so edit - // all non-core ones) - for(Map.Entry entry : editProperties.entrySet()) - { - QName qname = QName.createQName(entry.getKey()); - - if (!qname.getNamespaceURI().equals(NamespaceService.SYSTEM_MODEL_1_0_URI) || - qname.equals(ContentModel.PROP_LOCALE)) - { - // Update the property on the real node - getNodeService().setProperty(container, qname, (Serializable) entry.getValue()); - } - } - - return outcome; - } - - /** - * Init the editable Node - */ - protected Node initEditableNode() - { - Node currentNode = this.browseBean.getDocument(); - - if(ContentModel.TYPE_MULTILINGUAL_CONTAINER.equals(currentNode.getType())) - { - return currentNode; - } - else - { - return new Node( - getMultilingualContentService().getTranslationContainer( - currentNode.getNodeRef()) - ); - } - - } - - /** - * @return the editableNode - */ - public Node getEditableNode() - { - return editableNode; - } - - @Override - protected String doPostCommitProcessing(FacesContext context, String outcome) - { - this.browseBean.getDocument().reset(); - - return outcome; - } - - - // ------------------------------------------------------------------------------ - // Bean getters and setters - - /** - * @return the multilingualContentService - */ - public MultilingualContentService getMultilingualContentService() - { - if (multilingualContentService == null) - { - multilingualContentService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getMultilingualContentService(); - } - return multilingualContentService; - } - - /** - * @param multilingualContentService the multilingualContentService to set - */ - public void setMultilingualContentService( - MultilingualContentService multilingualContentService) { - this.multilingualContentService = multilingualContentService; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/ml/MakeMultilingualDialog.java b/war/src/main/java/org/alfresco/web/bean/ml/MakeMultilingualDialog.java deleted file mode 100644 index d059960b7a..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/ml/MakeMultilingualDialog.java +++ /dev/null @@ -1,297 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.ml; - -import java.util.Locale; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.model.SelectItem; - -import org.springframework.extensions.surf.util.I18NUtil; -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.ml.MultilingualContentService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.users.UserPreferencesBean; - -/** - * Dialog bean to make a node multilingual - * - * @author Yannick Pignot - */ -public class MakeMultilingualDialog extends BaseDialogBean -{ - private static final long serialVersionUID = -2862474360129631088L; - - transient private MultilingualContentService multilingualContentService; - - private UserPreferencesBean userPreferencesBean; - - /** if needed, add a new translation with content after this dialog closed */ - public static final String OPT_ADD_WITH_CONTENT = "ADD_WITH_CONTENT"; - /** if needed, add a new translation without content after this dialog closed */ - public static final String OPT_ADD_WITHOUT_CONTENT = "ADD_WITHOUT_CONTENT"; - - // The author is a mandatory properties - private String author; - - // The langage of the node to make multilingual - private String language; - - // set to true, a new translation will be added at the end of this dialog - private boolean addTranslationAfter = true; - - // set if the new translation to add will be an empty document or not - private String addingMode = OPT_ADD_WITH_CONTENT; - - // the node to edit - protected Node editableNode; - - - @Override - public void init(Map parameters) - { - super.init(parameters); - - // setup the editable node - this.editableNode = initEditableNode(); - - NodeRef nodeRef = this.editableNode.getNodeRef(); - - // propose the author and the language of the content for the properties of the MLContainer - if (this.getNodeService().hasAspect(nodeRef, ContentModel.ASPECT_AUTHOR) == true - && this.getNodeService().getProperty(nodeRef, ContentModel.PROP_AUTHOR) != null) - { - setAuthor((String) this.getNodeService().getProperty(nodeRef, ContentModel.PROP_AUTHOR)); - } - else - { - setAuthor(""); - } - - if (this.getNodeService().hasAspect(nodeRef, ContentModel.ASPECT_LOCALIZED) == true - && this.getNodeService().getProperty(nodeRef, ContentModel.PROP_LOCALE) != null) - { - setLanguage(((Locale) this.getNodeService().getProperty(nodeRef, ContentModel.PROP_LOCALE)).toString()); - } - else - { - setLanguage(null); - } - - addTranslationAfter = false; - addingMode = OPT_ADD_WITH_CONTENT; - } - - /** - * Init the editable Node - */ - protected Node initEditableNode() - { - return new Node(this.browseBean.getDocument().getNodeRef()); - } - - /* (non-Javadoc) - * @see org.alfresco.web.bean.dialog.BaseDialogBean#finishImpl(javax.faces.context.FacesContext, java.lang.String) - */ - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - Locale locale = I18NUtil.parseLocale(getLanguage()); - - NodeRef nodeRef = this.editableNode.getNodeRef(); - - // make this node multilingual - getMultilingualContentService().makeTranslation(nodeRef, locale); - NodeRef mlContainer = getMultilingualContentService().getTranslationContainer(nodeRef); - - // if the author of the node is not set, set it with the default author name of - // the new ML Container - String nodeAuthor = (String) getNodeService().getProperty(nodeRef, ContentModel.PROP_AUTHOR); - if (nodeAuthor == null || nodeAuthor.length() < 1) - getNodeService().setProperty(nodeRef, ContentModel.PROP_AUTHOR, getAuthor()); - - // set properties of the ml container - getNodeService().setProperty(mlContainer, ContentModel.PROP_AUTHOR, getAuthor()); - - return outcome; - } - - /* (non-Javadoc) - * @see org.alfresco.web.bean.dialog.BaseDialogBean#doPostCommitProcessing(javax.faces.context.FacesContext, java.lang.String) - */ - @Override - protected String doPostCommitProcessing(FacesContext context, String outcome) - { - // reset the document held by the browse bean as it's just been updated - this.browseBean.getDocument().reset(); - - // go to the set add translation dialog if asked - // to otherwise just return - if (this.addTranslationAfter) - { - if(addingMode.equalsIgnoreCase(OPT_ADD_WITHOUT_CONTENT)) - { - return "dialog:addTranslationWithoutContent"; - } - else - { - AddTranslationDialog dialog = (AddTranslationDialog) FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), "AddTranslationDialog"); - dialog.start(null); - return "dialog:addTranslation"; - } - } - - // close the dialog - return outcome; - } - - @Override - public boolean getFinishButtonDisabled() - { - return !(author != null && author.length() != 0 && language != null && language.length() != 0); - } - - - // ------------------------------------------------------------------------------ - // Bean getters and setters - - /** - * Returns the node being edited - * - * @return The node being edited - */ - public Node getEditableNode() - { - return this.editableNode; - } - - /** - * @return the author of the new created MLContainer - */ - public String getAuthor() - { - return author; - } - - /** - * @param author the author of new created MLContainer - */ - public void setAuthor(String author) - { - this.author = author; - } - - /** - * @return if a new translation must be added after this dialog closes - */ - public boolean isAddTranslationAfter() - { - return addTranslationAfter; - } - - /** - * @param addTranslationAfter set to true, a new translation will be added after this dialog closes - */ - public void setAddTranslationAfter(boolean addTranslationAfter) - { - this.addTranslationAfter = addTranslationAfter; - } - - /** - * @return the language of the translation - */ - public String getLanguage() - { - return language; - } - - /** - * @param language the language of the translation - */ - public void setLanguage(String language) - { - this.language = language; - } - - /** - * @param editableNode the node will become a multilingual - */ - public void setEditableNode(Node editableNode) - { - this.editableNode = editableNode; - } - - /** - * @return if the new translation must be added at the end of this dialog, - * this mode defines if the translation will be an empty document or not - */ - public String getAddingMode() - { - return addingMode; - } - - /** - * @param addingMode if the new translation must be added at the end of this dialog, - * this mode defines if the translation will be an empty document or not - */ - public void setAddingMode(String addingMode) - { - this.addingMode = addingMode; - } - - /** - * @return the complete list of available languages for the multilinguism - */ - public SelectItem[] getFilterLanguages() - { - return userPreferencesBean.getContentFilterLanguages(false); - } - - public void setMultilingualContentService( - MultilingualContentService multilingualContentService) - { - this.multilingualContentService = multilingualContentService; - } - - private MultilingualContentService getMultilingualContentService() - { - if (multilingualContentService == null) - { - multilingualContentService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getMultilingualContentService(); - } - return multilingualContentService; - } - - public void setUserPreferencesBean(UserPreferencesBean userPreferencesBean) - { - this.userPreferencesBean = userPreferencesBean; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/ml/MultilingualManageDialog.java b/war/src/main/java/org/alfresco/web/bean/ml/MultilingualManageDialog.java deleted file mode 100644 index 1a587ba871..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/ml/MultilingualManageDialog.java +++ /dev/null @@ -1,549 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.ml; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.ml.ContentFilterLanguagesService; -import org.alfresco.service.cmr.ml.EditionService; -import org.alfresco.service.cmr.ml.MultilingualContentService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.version.Version; -import org.alfresco.service.cmr.version.VersionHistory; -import org.alfresco.service.cmr.version.VersionService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.servlet.DownloadContentServlet; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.MapNode; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIPanel.ExpandedEvent; - -public class MultilingualManageDialog extends BaseDialogBean -{ - private static final long serialVersionUID = 4168804472130450812L; - - private final String MSG_MANAGE_DETAILS_FOR="manage_multilingual_details_for"; - private static final String MSG_CURRENT = "current"; - private static final String ML_VERSION_PANEL_ID = "ml-versions-panel"; - private static final String MSG_CLOSE = "close"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - protected Map panels = new HashMap(4, 1.0f); - - transient private MultilingualContentService multilingualContentService; - transient private ContentFilterLanguagesService contentFilterLanguagesService; - transient private EditionService editionService; - transient private VersionService versionService; - - private Node translationDocument; - - /** For the client side iteration on the edition hitories list, it represents the index of the list */ - private int currentEditionCursorPosition; - - /** List of client light weight edition histories */ - private List editionHistory = null; - - /** - * Returns the document this bean is currently representing - * - * @return The document Node - */ - public Node getDocument() - { - return this.getNode(); - } - - /** - * Returns the Node this bean is currently representing - * - * @return The Node - */ - public Node getNode() - { - return this.browseBean.getDocument(); - } - - /** - * @param multilingualContentService the multilingual ContentService to set - */ - public void setMultilingualContentService(MultilingualContentService multilingualContentService) - { - this.multilingualContentService = multilingualContentService; - } - - /** - * @return multilingualContentService - */ - protected MultilingualContentService getMultilingualContentService() - { - //check for null for cluster environment - if (multilingualContentService == null) - { - multilingualContentService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getMultilingualContentService(); - } - return multilingualContentService; - } - - /** - * @param contentFilterLanguagesService The Content Filter Languages Service to set. - */ - public void setContentFilterLanguagesService(ContentFilterLanguagesService contentFilterLanguagesService) - { - this.contentFilterLanguagesService = contentFilterLanguagesService; - } - - /** - * @return contentFilterLanguagesService - */ - protected ContentFilterLanguagesService getContentFilterLanguagesService() - { - //check for null for cluster environment - if (contentFilterLanguagesService == null) - { - contentFilterLanguagesService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getContentFilterLanguagesService(); - } - return contentFilterLanguagesService; - } - - /** - * @param editionService The Edition Service to set. - */ - public void setEditionService(EditionService editionService) - { - this.editionService = editionService; - } - - /** - * @return editionService - */ - protected EditionService getEditionService() - { - //check for null for cluster environment - if (editionService == null) - { - editionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getEditionService(); - } - return editionService; - } - - /** - * Sets the version service instance the bean should use - * - * @param versionService The VersionService - */ - public void setVersionService(VersionService versionService) - { - this.versionService = versionService; - } - - /** - * @return versionService - */ - protected VersionService getVersionService() - { - //check for null for cluster environment - if (versionService == null) - { - versionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getVersionService(); - } - return versionService; - } - - /** - * Before opening the ml container details, remeber the translation - * from which the action comes. - * - * @param node - */ - public void setTranslationDocument(Node node) - { - this.translationDocument = node; - } - - /** - * @return Returns the panels expanded state map. - */ - public Map getPanels() - { - return this.panels; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_MANAGE_DETAILS_FOR) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) - + getDocument().getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } - - /** - * Returns a list of objects representing the translations of the current document - * - * @return List of translations - */ - public List getTranslations() - { - List translations = new ArrayList(); - - Node document = getDocument(); - - boolean canNewEdtion = MultilingualUtils.canStartNewEditon(document, FacesContext.getCurrentInstance()); - - if (document.hasAspect(ContentModel.ASPECT_MULTILINGUAL_DOCUMENT) || ContentModel.TYPE_MULTILINGUAL_CONTAINER.equals(document.getType())) - { - Map translationsMap = getMultilingualContentService().getTranslations(getDocument().getNodeRef()); - - if (translationsMap != null && translationsMap.size() > 0) - { - for (Map.Entry entry : translationsMap.entrySet()) - { - NodeRef nodeRef = (NodeRef) entry.getValue(); - - // create a map node representation of the translation - MapNode mapNode = new MapNode(nodeRef); - - Locale locale = (Locale) getNodeService().getProperty(nodeRef, ContentModel.PROP_LOCALE); - - String lgge = (locale != null) ? - // convert the locale into new ISO codes - getContentFilterLanguagesService().convertToNewISOCode(locale.getLanguage()).toUpperCase() - : null; - - mapNode.put("name", getNodeService().getProperty(nodeRef, ContentModel.PROP_NAME)); - mapNode.put("language", lgge); - mapNode.put("url", DownloadContentServlet.generateBrowserURL(nodeRef, mapNode.getName())); - - boolean isEmpty = new Boolean(getNodeService().hasAspect(nodeRef, ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION)); - - mapNode.put("notEmpty", !isEmpty); - mapNode.put("userHasRight", new Boolean(canNewEdtion && !isEmpty)); - // add the client side version to the list - translations.add(mapNode); - } - } - } - - return translations; - } - - /** - * Init the mlContainer histories and returns an empty list to fill a rich list value without content. - * - * @return an empty list - */ - public List getEmptyListAndInitEditions() - { - // this call ensures that the edition of the mlContainer must be - // re-initialized. - - // remove each old mlContainer's translations of the panel list - List panelsToRemove = new ArrayList(); - for(Map.Entry panel : panels.entrySet()) - { - if(panel.getKey().startsWith(ML_VERSION_PANEL_ID)) - { - //panels.remove(panel.getKey()); - panelsToRemove.add(panel.getKey()); - } - } - - for(String panelId : panelsToRemove) - { - panels.remove(panelId); - } - - // init the Edition histories - initEditionHistory(); - currentEditionCursorPosition = -1; - - return new ArrayList(0); - } - - /** - * For the client side iteration on the edition hitories list, returns the number of editions. - * - * @return the number of edition of the current mlContainer - */ - public int getEditionSize() - { - // return the size of the list - return editionHistory.size(); - } - - /** - * For the client side iteration on the edition hitories list, - * return the next edition history. - * - * @return a light weight representation of an edition history - */ - public SingleEditionBean getNextSingleEditionBean() - { - currentEditionCursorPosition++; - - return getCurrentSingleEditionBean(); - } - - /** - * For the client side iteration on the edition hitories list, - * return the current edition history. - * - * @return a light weight representation of an edition history - */ - public SingleEditionBean getCurrentSingleEditionBean() - { - if (currentEditionCursorPosition < getEditionSize()) - { - return editionHistory.get(currentEditionCursorPosition); - } - - return null; - } - - /** - * Restore the translationf from which the ml container - * details dialog comes. - */ - public void resetMLDocument(ActionEvent event) - { - this.browseBean.setupCommonBindingProperties(this.translationDocument); - this.browseBean.setDocument(this.translationDocument); - } - - /** - * Action handler to remove a custom view template from the current node - */ - public void removeTemplate(ActionEvent event) - { - try - { - // clear template property - this.getNodeService().setProperty(getNode().getNodeRef(), ContentModel.PROP_TEMPLATE, null); - this.getNodeService().removeAspect(getNode().getNodeRef(), ContentModel.ASPECT_TEMPLATABLE); - - // reset node details for next refresh of details page - getNode().reset(); - } - catch (Exception e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), e.getMessage()), e); - } - } - - /** - * Save the state of the panel that was expanded/collapsed - */ - public void expandPanel(ActionEvent event) - { - if (event instanceof ExpandedEvent) - { - String id = event.getComponent().getId(); - // we prefix some panels with "no-" which we remove to give consistent behaviour in the UI - if (id.startsWith("no-") == true) - { - id = id.substring(3); - } - this.panels.put(id, ((ExpandedEvent)event).State); - } - - String id = event.getComponent().getId(); - - if(id.startsWith(ML_VERSION_PANEL_ID)) - { - this.currentEditionCursorPosition = Integer.parseInt(id.substring("ml-versions-panel".length())) - 1; - } - } - - - /** - * Returns the ml container of the document this bean is currently representing - * - * @return The document multilingual container NodeRef - */ - public Node getDocumentMlContainer() - { - Node currentNode = getNode(); - - if(ContentModel.TYPE_MULTILINGUAL_CONTAINER.equals(currentNode.getType())) - { - return currentNode; - } - else - { - NodeRef nodeRef = getNode().getNodeRef(); - - return new Node(getMultilingualContentService().getTranslationContainer(nodeRef)); - } - } - - /** - * Constructs a list of objects representing the editions of the - * logical document - * - * @return List of editions - */ - private List initEditionHistory() - { - // get the mlContainer - NodeRef mlContainer = getDocumentMlContainer().getNodeRef(); - - // get all editions (in descending order - ie. most recent first) - List orderedEditionList = new ArrayList(getEditionService().getEditions(mlContainer).getAllVersions()); - - // the list of Single Edition Bean to return - editionHistory = new ArrayList(orderedEditionList.size()); - - boolean firstEdition = true; - - // for each edition, init a SingleEditionBean - for (Version edition : orderedEditionList) - { - SingleEditionBean editionBean = new SingleEditionBean(); - - MapNode clientEdition = new MapNode(edition.getFrozenStateNodeRef()); - - String editionLabel = edition.getVersionLabel(); - if (firstEdition) - { - editionLabel += " (" + Application.getMessage(FacesContext.getCurrentInstance(), MSG_CURRENT) + ")"; - } - - clientEdition.put("editionLabel", editionLabel); - clientEdition.put("editionNotes", edition.getDescription()); - clientEdition.put("editionAuthor", edition.getCreator()); - clientEdition.put("editionDate", edition.getCreatedDate()); - - // Set the edition of the edition bean - editionBean.setEdition(clientEdition); - - // get translations - List translationHistories = null; - - if (firstEdition) - { - // Get the translations because the current edition doesn't content link with its - // translation in the version store. - Map translations = getMultilingualContentService().getTranslations(mlContainer); - translationHistories = new ArrayList(translations.size()); - for (NodeRef translation : translations.values()) - { - translationHistories.add(getVersionService().getVersionHistory(translation)); - } - } - else - { - translationHistories = getEditionService().getVersionedTranslations(edition); - } - - // add each translation in the SingleEditionBean - for (VersionHistory versionHistory : translationHistories) - { - for (Version checkVersion : versionHistory.getAllVersions()) - { - NodeRef frozenStateNodeRef = checkVersion.getFrozenStateNodeRef(); - if (frozenStateNodeRef.getStoreRef().getIdentifier().equals("lightWeightVersionStore")) - { - // It's the old one pulled back by serialization - // Repopulate the version history - NodeRef versionedNodeRef = checkVersion.getVersionedNodeRef(); - versionHistory = versionService.getVersionHistory(versionedNodeRef); - break; - } - } - - // get the list of versions (in descending order - ie. most recent first) - List orderedVersions = new ArrayList(versionHistory.getAllVersions()); - - // the last version (ie. most recent) is the first version of the list - Version lastVersion = orderedVersions.get(0); - - // get the properties of the lastVersion - Map lastVersionProperties = getEditionService().getVersionedMetadatas(lastVersion); - Locale language = (Locale) lastVersionProperties.get(ContentModel.PROP_LOCALE); - - // create a map node representation of the last version - MapNode clientLastVersion = new MapNode(lastVersion.getFrozenStateNodeRef()); - - clientLastVersion.put("versionName", lastVersionProperties.get(ContentModel.PROP_NAME)); - // use the node service for the description to ensure that the returned value is a text and not a MLText - clientLastVersion.put("versionDescription", getNodeService().getProperty(lastVersion.getFrozenStateNodeRef(), ContentModel.PROP_DESCRIPTION)); - clientLastVersion.put("versionAuthor", lastVersionProperties.get(ContentModel.PROP_AUTHOR)); - clientLastVersion.put("versionCreatedDate", lastVersionProperties.get(ContentModel.PROP_CREATED)); - clientLastVersion.put("versionModifiedDate", lastVersionProperties.get(ContentModel.PROP_MODIFIED)); - clientLastVersion.put("versionLanguage", getContentFilterLanguagesService().convertToNewISOCode(language.getLanguage()).toUpperCase()); - - if(getNodeService().hasAspect(lastVersion.getFrozenStateNodeRef(), ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION)) - { - clientLastVersion.put("versionUrl", null); - } - else - { - clientLastVersion.put("versionUrl", DownloadContentServlet.generateBrowserURL(lastVersion.getFrozenStateNodeRef(), clientLastVersion.getName())); - } - - // add a translation of the editionBean - editionBean.addTranslations(clientLastVersion); - } - editionHistory.add(editionBean); - firstEdition = false; - } - - return editionHistory; - } - @Override - protected String getDefaultCancelOutcome() - { - resetMLDocument(null); - return "dialog:close"; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/ml/MultilingualUtils.java b/war/src/main/java/org/alfresco/web/bean/ml/MultilingualUtils.java deleted file mode 100644 index d8b3923669..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/ml/MultilingualUtils.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.ml; - -import java.io.Serializable; -import java.util.Locale; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.ml.MultilingualContentService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.repository.Node; - -/** - * Util class for the management of multilingual documents on the web client side - * - * @author yanipig - */ -public class MultilingualUtils implements Serializable -{ - - private static final long serialVersionUID = 2218309432064312000L; - - /** - * Returns true if the current user has enough right to add a content to the space - * where the pivot translation is located in. - * - * @param multlingualDocument Node - * @param fc FacesContext - * @return boolean - */ - public static boolean canAddChildrenToPivotSpace(Node multlingualDocument, FacesContext fc) - { - MultilingualContentService mlservice = getMultilingualContentService(fc); - NodeService nodeService = getNodeService(fc); - - // get the pivot translation and get the space where it's located - NodeRef pivot = mlservice.getPivotTranslation(multlingualDocument.getNodeRef()); - NodeRef space = nodeService.getPrimaryParent(pivot).getParentRef(); - - // return if the current user can add a content to the space of the pivot - return new Node(space).hasPermission(PermissionService.ADD_CHILDREN); - } - - /** - * Returns true if the current user can delete each translation of the mlContainer of the given node - * - * @param multlingualDocument Node - * @param fc FacesContext - * @return boolean - */ - public static boolean canDeleteEachTranslation(Node multlingualDocument, FacesContext fc) - { - boolean can = true; - - MultilingualContentService mlservice = getMultilingualContentService(fc); - - Map translations = mlservice.getTranslations(multlingualDocument.getNodeRef()); - for (Map.Entry entry : translations.entrySet()) - { - Node translation = new Node(entry.getValue()); - - if(translation.hasPermission(PermissionService.DELETE_NODE) == false - || translation.isLocked() == true - || translation.hasAspect(ContentModel.ASPECT_WORKING_COPY) == true - ) - { - can = false; - break; - } - } - - return can; - } - - /** - * Returns true if the current user can move each translation of the mlContainer of the given node - * - * @param multlingualDocument Node - * @param fc FacesContext - * @return boolean - */ - public static boolean canMoveEachTranslation(Node multlingualDocument, FacesContext fc) - { - boolean can = true; - - MultilingualContentService mlservice = getMultilingualContentService(fc); - - Map translations = mlservice.getTranslations(multlingualDocument.getNodeRef()); - for (Map.Entry entry : translations.entrySet()) - { - Node translation = new Node(entry.getValue()); - - if(translation.hasPermission(PermissionService.DELETE_NODE) == false) - { - can = false; - break; - } - } - - return can; - } - - /** - * Returns true if the current user can delete each translation and create - * * a new content in the space - * - * @param multlingualDocument Node - * @param fc FacesContext - * @return boolean - */ - public static boolean canStartNewEditon(Node multlingualDocument, FacesContext fc) - { - boolean canDelete = MultilingualUtils.canMoveEachTranslation(multlingualDocument, fc); - boolean canCreate = MultilingualUtils.canAddChildrenToPivotSpace(multlingualDocument, fc); - - return canDelete && canCreate; - } - - private static MultilingualContentService getMultilingualContentService(FacesContext fc) - { - return (MultilingualContentService) FacesHelper.getManagedBean(fc, "MultilingualContentService"); - } - - private static NodeService getNodeService(FacesContext fc) - { - return (NodeService) FacesHelper.getManagedBean(fc, "NodeService"); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/ml/NewEditionWizard.java b/war/src/main/java/org/alfresco/web/bean/ml/NewEditionWizard.java deleted file mode 100644 index d007c06e5c..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/ml/NewEditionWizard.java +++ /dev/null @@ -1,618 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.ml; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.faces.model.DataModel; -import javax.faces.model.ListDataModel; - -import org.springframework.extensions.surf.util.I18NUtil; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.version.VersionModel; -import org.alfresco.service.cmr.lock.LockService; -import org.alfresco.service.cmr.lock.LockStatus; -import org.alfresco.service.cmr.ml.ContentFilterLanguagesService; -import org.alfresco.service.cmr.ml.EditionService; -import org.alfresco.service.cmr.ml.MultilingualContentService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.version.Version; -import org.alfresco.service.cmr.version.VersionService; -import org.alfresco.service.cmr.version.VersionType; -import org.springframework.extensions.surf.util.ParameterCheck; -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.wizard.BaseWizardBean; -import org.alfresco.web.ui.common.component.UIActionLink; - -/** - * Wizard bean to create a new edition from an existing MLContainer. - * - * @author Yanick Pignot - */ -public class NewEditionWizard extends BaseWizardBean -{ - private static final long serialVersionUID = 2078582486053536124L; - - public static final String ID_MESSAGE_MINOR_CHANGE = "minor_change"; - public static final String ID_MESSAGE_MAJOR_CHANGE = "major_change"; - - transient private EditionService editionService; - transient private MultilingualContentService multilingualContentService; - transient private ContentFilterLanguagesService contentFilterLanguagesService; - transient private LockService lockService; - transient private VersionService versionService; - - protected NodeRef mlContainerToVersion; - - private List selectableTranslations; - private List translationsCheckedOut; - - private String editionNotes; - private boolean minorChange; - private boolean otherProperties; - private boolean skipFirstStep; - private String language; - private String title; - private boolean hasTranslationCheckedOut; - private NodeRef startingElement; - private String author; - private String selectedLanguage; - - - @Override - public void init(Map parameters) - { - super.init(parameters); - - // reset the fileds - editionNotes = null; - minorChange = true; - otherProperties = false; - translationsCheckedOut = null; - selectableTranslations = null; - - - if(!skipFirstStep) - { - // this properties is set by the skipFirstStep action event method. - - language = null; - title = null; - - // set the current mlContainer - setMLContainer(); - } - - // init the list of the available translations and the list of translations checked out - initTranslationList(); - - // true if they are at leat one translation checked out - hasTranslationCheckedOut = this.translationsCheckedOut.size() > 0; - } - - /** - * Force the the lang of the new pivot translation for the new edition and skip the first step - */ - public void skipFirstStep(ActionEvent event) - { - skipFirstStep = true; - - // Get the lang of the new - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String lang = params.get("lang"); - - // test if the parameter is valid - ParameterCheck.mandatoryString("The lang of the node", lang); - - // set the current mlContainer - setMLContainer(); - - setStartingItem(lang.toLowerCase()); - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - // fill the edition properties - Map versionProperties = new HashMap(1, 1.0f); - versionProperties.put(Version.PROP_DESCRIPTION, editionNotes); - if (minorChange) - { - versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR); - } - else - { - versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR); - } - - // create the edition and get the reference of the new starting translation - NodeRef newPivot = getEditionService().createEdition(startingElement, versionProperties); - - // redirect the user at the 'modify translation properties' page if desire. - if (otherProperties == true) - { - this.browseBean.setDocument(new Node(newPivot)); - outcome = AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME + AlfrescoNavigationHandler.OUTCOME_SEPARATOR + AlfrescoNavigationHandler.DIALOG_PREFIX + "setContentProperties"; - } - else - { - outcome = AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME + AlfrescoNavigationHandler.OUTCOME_SEPARATOR + "browse"; - } - - skipFirstStep = false; - - return outcome; - } - - /** - * Returns the properties for checked out translations JSF DataModel - * - * @return JSF DataModel representing the translations checked out - */ - public DataModel getTranslationsCheckedOutDataModel() - { - return getDataModel(this.translationsCheckedOut); - } - - /** - * Returns the properties for available translations JSF DataModel - * - * @return JSF DataModel representing the available translation for a new edition - */ - public DataModel getAvailableTranslationsDataModel() - { - return getDataModel(this.selectableTranslations); - } - - /** - * Determines whether there are any translation checked out. - * - * @return true if there are translation checked out - */ - public boolean getHasTranslationCheckedOut() - { - return hasTranslationCheckedOut; - } - - @Override - public boolean getFinishButtonDisabled() - { - return super.getFinishButtonDisabled() || hasTranslationCheckedOut; - } - - @Override - public boolean getNextButtonDisabled() - { - return super.getNextButtonDisabled() || hasTranslationCheckedOut; - } - - /** - * @param language of the starting translation to set as the new pivot of the new edition - */ - private void setStartingItem(String language) - { - // get the starting point translation with its locale - startingElement = getMultilingualContentService().getTranslationForLocale(mlContainerToVersion, I18NUtil.parseLocale(language)); - - // set the futur properties of the new starting element (only usefull for the summary step) - setLanguage(language); - setTitle((String) getNodeService().getProperty(startingElement, ContentModel.PROP_TITLE)); - setAuthor((String) getNodeService().getProperty(startingElement, ContentModel.PROP_AUTHOR)); - } - - /** - * Util metho which construct a data model with rows passed in parameter - */ - private DataModel getDataModel(Object rows) - { - DataModel translationDataModel = new ListDataModel(); - - translationDataModel.setWrappedData(rows); - - return translationDataModel; - } - - /** - * Util method which init the lists of translations - */ - private void initTranslationList() - { - this.translationsCheckedOut = new ArrayList(); - this.selectableTranslations = new ArrayList(); - - // get all translations of the mlContainer - Map translations = getMultilingualContentService().getTranslations(mlContainerToVersion); - - // fill the data table rows list - for(Map.Entry entry : translations.entrySet()) - { - NodeRef nodeRef = entry.getValue(); - - String name = (String) getNodeService().getProperty(nodeRef, ContentModel.PROP_NAME); - String langCode = ((Locale) getNodeService().getProperty(nodeRef, ContentModel.PROP_LOCALE)).getLanguage(); - String langText = getContentFilterLanguagesService().getLabelByCode(langCode); - String lockOwner = (String) getNodeService().getProperty(nodeRef, ContentModel.PROP_LOCK_OWNER); - - // create the row with the current translation - TranslationWrapper wrapper = new TranslationWrapper(name, langCode, lockOwner, langText); - - if(!getNodeService().hasAspect(nodeRef, ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION)) - { - // add it to the selectable list if it is not empty - this.selectableTranslations.add(wrapper); - } - - if(getNodeService().hasAspect(nodeRef, ContentModel.ASPECT_LOCKABLE)) - { - LockStatus lockStatus = getLockService().getLockStatus(nodeRef); - if (lockStatus != LockStatus.NO_LOCK) - { - // if the node is locked, add it to the locked translation list - this.translationsCheckedOut.add(wrapper); - } - } - - } - } - - private void setMLContainer() - { - // set the mlContainer to version - NodeRef currentNodeRef = this.browseBean.getDocument().getNodeRef(); - - if(ContentModel.TYPE_MULTILINGUAL_CONTAINER.equals(getNodeService().getType(currentNodeRef))) - { - mlContainerToVersion = currentNodeRef; - } - else - { - mlContainerToVersion = getMultilingualContentService().getTranslationContainer(currentNodeRef); - } - - if(!skipFirstStep) - { - // init the pivot language (it will be selected by default) - selectedLanguage = ((Locale) getNodeService().getProperty(mlContainerToVersion, ContentModel.PROP_LOCALE)).getLanguage(); - } - } - - /** - * @return the edition notes - */ - public String getEditionNotes() - { - return editionNotes; - } - - /** - * @param editionNotes the edition notes to set - */ - public void setEditionNotes(String editionNotes) - { - this.editionNotes = editionNotes; - } - - /** - * @return the minorChange get if the new edition is minor or not. - */ - public boolean isMinorChange() - { - return minorChange; - } - - /** - * @param minorChange set if the new edition is minor or not. - */ - public void setMinorChange(boolean minorChange) - { - this.minorChange = minorChange; - } - - /** - * @return the otherProperties, get if the edit details dialog must be set at the end of the wizard - */ - public boolean isOtherProperties() - { - return otherProperties; - } - - /** - * @param otherProperties set as true, the edit details dialog must be set at the end of the wizard - */ - public void setOtherProperties(boolean otherProperties) - { - this.otherProperties = otherProperties; - } - - /** - * @return the author - */ - public String getAuthor() - { - return author; - } - - - /** - * @return the language - */ - public String getLanguage() - { - return getContentFilterLanguagesService().getLabelByCode(language); - } - - - /** - * @param language the language to set - */ - public void setLanguage(String language) - { - this.language = language; - } - - /** - * @param locale the language to set - */ - public void setLanguage(Locale locale) - { - this.language = locale.getLanguage(); - } - - /** - * @return the title - */ - public String getTitle() - { - return title; - } - - - /** - * @param title the title to set - */ - public void setTitle(String title) - { - this.title = title; - } - - /** - * @param author the author to set - */ - public void setAuthor(String author) - { - this.author = author; - } - - - /** - * @return the versionLabel - */ - public String getVersionLabel() - { - String label = getVersionService().getCurrentVersion(mlContainerToVersion).getVersionLabel(); - - String nextLabel = null; - - try - { - int dotPosition = label.indexOf('.'); - - int major = Integer.parseInt(label.substring(0, dotPosition)); - int minor = Integer.parseInt(label.substring(dotPosition + 1)); - - if(minorChange) - { - nextLabel = major + "." + (minor + 1); - } - else - { - nextLabel = (major + 1) + ".0"; - } - } - catch(Exception e) - { - nextLabel = ""; - } - - if(minorChange) - { - String minorString = Application.getMessage( - FacesContext.getCurrentInstance(), - ID_MESSAGE_MINOR_CHANGE); - - return nextLabel + " (" + minorString + ')' ; - } - else - { - return nextLabel; - } - } - - - - /** - * @return the selectedTranslationLanguage - */ - public String getSelectedTranslationLanguage() - { - return selectedLanguage; - } - - /** - * @param language the selectedTranslationLanguage to set - */ - public void setSelectedTranslationLanguage(String language) - { - // only the selected language is not set as null - if(language != null) - { - setStartingItem(language); - } - - } - - - /** - * @param multilingualContentService the Multilingual Content Service to set - */ - public void setMultilingualContentService(MultilingualContentService multilingualContentService) - { - this.multilingualContentService = multilingualContentService; - } - - protected MultilingualContentService getMultilingualContentService() - { - if (multilingualContentService == null) - { - multilingualContentService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getMultilingualContentService(); - } - return multilingualContentService; - } - - /** - * @param contentFilterLanguagesService the Content Filter Languages Service to set - */ - public void setContentFilterLanguagesService(ContentFilterLanguagesService contentFilterLanguagesService) - { - this.contentFilterLanguagesService = contentFilterLanguagesService; - } - - protected ContentFilterLanguagesService getContentFilterLanguagesService() - { - if (contentFilterLanguagesService == null) - { - contentFilterLanguagesService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getContentFilterLanguagesService(); - } - return contentFilterLanguagesService; - } - - - /** - * @param lockService the Lock Service to set - */ - public void setLockService(LockService lockService) - { - this.lockService = lockService; - } - - protected LockService getLockService() - { - if (lockService == null) - { - lockService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getLockService(); - } - return lockService; - } - - /** - * @param editionService the Edition Service to set - */ - public void setEditionService(EditionService editionService) - { - this.editionService = editionService; - } - - protected EditionService getEditionService() - { - if (editionService == null) - { - editionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getEditionService(); - } - return editionService; - } - - /** - * @param versionService the version Service to set - */ - public void setVersionService(VersionService versionService) - { - this.versionService = versionService; - } - - protected VersionService getVersionService() - { - if (versionService == null) - { - versionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getVersionService(); - } - return versionService; - } - - - /** - * Simple wrapper class to represent a translation in the data table - */ - public static class TranslationWrapper implements Serializable - { - private static final long serialVersionUID = 5517785385414245587L; - - private String language; - private String name; - private String checkedOutBy; - private String languageLabel; - - public TranslationWrapper(String name, String language, String checkedOutBy, String languageLabel) - { - this.name = name; - this.language = language; - this.checkedOutBy = checkedOutBy; - this.languageLabel = languageLabel; - } - - public String getCheckedOutBy() - { - return checkedOutBy; - } - - public String getLanguage() - { - return language; - } - - public String getName() - { - return name; - } - - public String getLanguageLabel() - { - return this.languageLabel; - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/ml/SingleEditionBean.java b/war/src/main/java/org/alfresco/web/bean/ml/SingleEditionBean.java deleted file mode 100644 index 0e20535f37..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/ml/SingleEditionBean.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.ml; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import org.alfresco.web.bean.repository.MapNode; - -/** - * Util class which represents a light weight representation of an edition history for the - * client side needs. - * - * @author pignoya - */ -public class SingleEditionBean implements Serializable -{ - private static final long serialVersionUID = 9145202732094403340L; - - /** The edition in a list */ - private List edition = null; - - /** The translation list of the edition */ - private List translations = null; - - /** - * @return String - */ - public String getEditionLabel() - { - return (String) this.getEdition().get(0).get("editionLabel"); - } - - /** - * @return the edition - */ - public List getEdition() - { - return edition; - } - - /** - * @param edition the edition to set - */ - public void setEdition(MapNode edition) - { - this.edition = new ArrayList(1); - translations = null; - - this.edition.add(edition); - } - - /** - * @return the translations - */ - public List getTranslations() - { - return translations; - } - - /** - * @param translation the translations to add to the list - */ - public void addTranslations(MapNode translation) - { - if (this.translations == null) - { - this.translations = new ArrayList(); - } - - this.translations.add(translation); - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/bean/preview/BasePreviewBean.java b/war/src/main/java/org/alfresco/web/bean/preview/BasePreviewBean.java deleted file mode 100644 index 881564408d..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/preview/BasePreviewBean.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.preview; - -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.web.scripts.FileTypeImageUtils; -import org.alfresco.service.cmr.repository.FileTypeImageSize; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.TemplateImageResolver; -import org.alfresco.web.bean.BrowseBean; -import org.alfresco.web.bean.NavigationBean; -import org.alfresco.web.bean.TemplateSupportBean; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; - -/** - * Backing bean for the Preview Document in Template action page - * - * @author Kevin Roast - */ -public abstract class BasePreviewBean extends BaseDialogBean -{ - /** BrowseBean instance */ - protected BrowseBean browseBean; - - /** The NavigationBean bean reference */ - protected NavigationBean navigator; - - /** The selected Template Id */ - protected NodeRef template; - - - /** - * @param browseBean The BrowseBean to set. - */ - public void setBrowseBean(BrowseBean browseBean) - { - this.browseBean = browseBean; - } - - /** - * @param navigator The NavigationBean to set. - */ - public void setNavigator(NavigationBean navigator) - { - this.navigator = navigator; - } - - /** - * Returns the node this bean is currently working with - * - * @return The current Node - */ - public abstract Node getNode(); - - /** - * Returns the id of the current node - * - * @return The id - */ - public String getId() - { - return getNode().getId(); - } - - /** - * Returns the name of the current node - * - * @return Name of the current node - */ - public String getName() - { - return getNode().getName(); - } - - /** - * Returns a model for use by the template on the Preview page. - * - * @return model containing current document/space info. - */ - public abstract Map getTemplateModel(); - - /** Template Image resolver helper */ - protected TemplateImageResolver imageResolver = new TemplateImageResolver() - { - public String resolveImagePathForName(String filename, FileTypeImageSize size) - { - return FileTypeImageUtils.getFileTypeImage(FacesContext.getCurrentInstance(), filename, size); - } - }; - - /** - * @return the current template as a full NodeRef - */ - public NodeRef getTemplateRef() - { - return this.template; - } - - /** - * @return Returns the template Id. - */ - public String getTemplate() - { - return (this.template != null ? this.template.getId() : null); - } - - /** - * @param template The template Id to set. - */ - public void setTemplate(String template) - { - if (template != null && template.equals(TemplateSupportBean.NO_SELECTION) == false) - { - this.template = new NodeRef(Repository.getStoreRef(), template); - } - } - - private int findNextPreviewNode(List nodes, int start) - { - // search from start to end of list - for (int i=start; i nodes, int start) - { - // search from start to beginning of list - for (int i=start; i>=0; i--) - { - Node next = nodes.get(i); - if (next.hasAspect(ContentModel.ASPECT_TEMPLATABLE)) - { - return i; - } - } - // end of list to start + 1 (to skip original node) - for (int i=nodes.size() - 1; i>start; i--) - { - Node next = nodes.get(i); - if (next.hasAspect(ContentModel.ASPECT_TEMPLATABLE)) - { - return i; - } - } - return -1; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/preview/DocumentPreviewBean.java b/war/src/main/java/org/alfresco/web/bean/preview/DocumentPreviewBean.java deleted file mode 100644 index 4d3a93d0e8..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/preview/DocumentPreviewBean.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.preview; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.TemplateService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.NavigationSupport; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.NodeListUtils; -import org.alfresco.web.ui.common.NodePropertyComparator; -import org.alfresco.web.ui.common.component.UIActionLink; - -/** - * Backing bean for the Preview Document in Template action page - * - * @author Kevin Roast - */ -public class DocumentPreviewBean extends BasePreviewBean implements NavigationSupport -{ - private static final long serialVersionUID = 2476545866710371333L; - - private final static String MSG_PREVIEW_OF = "preview_of"; - private final static String MSG_CLOSE = "close"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - /** - * Returns the document this bean is currently representing - * - * @return The document Node - */ - public Node getNode() - { - return this.browseBean.getDocument(); - } - - /** - * Returns a model for use by a template on the Document Details page. - * - * @return model containing current document and current space info. - */ - @SuppressWarnings("unchecked") - public Map getTemplateModel() - { - HashMap model = new HashMap(3, 1.0f); - - model.put("document", getNode().getNodeRef()); - model.put("space", this.navigator.getCurrentNode().getNodeRef()); - model.put(TemplateService.KEY_IMAGE_RESOLVER, imageResolver); - - return model; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - public String getCurrentItemId() - { - return getId(); - } - - public String getOutcome() - { - return "dialog:close:dialog:previewContent"; - } - - public void nextItem(ActionEvent event) - { - UIActionLink link = (UIActionLink) event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - List nodes = this.browseBean.getContent(); - if (nodes.size() > 1) - { - String currentSortColumn = this.browseBean.getContentRichList().getCurrentSortColumn(); - boolean currentSortDescending = this.browseBean.getContentRichList().isCurrentSortDescending(); - Collections.sort(nodes, new NodePropertyComparator(currentSortColumn, !currentSortDescending)); - Node next = NodeListUtils.nextItem(nodes, id); - this.browseBean.setupContentAction(next.getId(), false); - } - } - } - - public void previousItem(ActionEvent event) - { - UIActionLink link = (UIActionLink) event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - List nodes = this.browseBean.getContent(); - if (nodes.size() > 1) - { - String currentSortColumn = this.browseBean.getContentRichList().getCurrentSortColumn(); - boolean currentSortDescending = this.browseBean.getContentRichList().isCurrentSortDescending(); - Collections.sort(nodes, new NodePropertyComparator(currentSortColumn, !currentSortDescending)); - Node previous = NodeListUtils.previousItem(nodes, id); - this.browseBean.setupContentAction(previous.getId(), false); - } - } - } - - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_PREVIEW_OF) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) + getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/preview/SpacePreviewBean.java b/war/src/main/java/org/alfresco/web/bean/preview/SpacePreviewBean.java deleted file mode 100644 index bcee20b669..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/preview/SpacePreviewBean.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.preview; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.TemplateService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.NavigationSupport; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.NodeListUtils; -import org.alfresco.web.ui.common.NodePropertyComparator; -import org.alfresco.web.ui.common.component.UIActionLink; - -/** - * Backing bean for the Preview Space in Template action page - * - * @author Kevin Roast - */ -public class SpacePreviewBean extends BasePreviewBean implements NavigationSupport -{ - private static final long serialVersionUID = -4766291793031654901L; - private final static String MSG_PREVIEW_OF = "preview_of"; - private final static String MSG_CLOSE = "close"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - /** - * Returns the Space this bean is currently representing - * - * @return The Space Node - */ - public Node getNode() - { - return this.browseBean.getActionSpace(); - } - - /** - * Returns a model for use by a template on the Document Details page. - * - * @return model containing current document and current space info. - */ - @SuppressWarnings("unchecked") - public Map getTemplateModel() - { - HashMap model = new HashMap(3, 1.0f); - - model.put("space", getNode().getNodeRef()); - model.put(TemplateService.KEY_IMAGE_RESOLVER, imageResolver); - - return model; - } - - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - public String getCurrentItemId() - { - return getId(); - } - - public String getOutcome() - { - return "dialog:close:dialog:previewSpace"; - } - - public void nextItem(ActionEvent event) - { - UIActionLink link = (UIActionLink) event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - NodeRef currNodeRef = new NodeRef(Repository.getStoreRef(), id); - List nodes = this.browseBean.getParentNodes(currNodeRef); - Node next = null; - if (nodes.size() > 1) - { - String currentSortColumn = this.browseBean.getSpacesRichList().getCurrentSortColumn(); - boolean currentSortDescending = this.browseBean.getSpacesRichList().isCurrentSortDescending(); - Collections.sort(nodes, new NodePropertyComparator(currentSortColumn, !currentSortDescending)); - next = NodeListUtils.nextItem(nodes, id); - this.browseBean.setupSpaceAction(next.getId(), false); - } - if (next == null) - { - Node currNode = new Node(currNodeRef); - this.navigator.setupDispatchContext(currNode); - } - } - - } - - public void previousItem(ActionEvent event) - { - UIActionLink link = (UIActionLink) event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - NodeRef currNodeRef = new NodeRef(Repository.getStoreRef(), id); - List nodes = this.browseBean.getParentNodes(currNodeRef); - Node previous = null; - if (nodes.size() > 1) - { - String currentSortColumn = this.browseBean.getSpacesRichList().getCurrentSortColumn(); - boolean currentSortDescending = this.browseBean.getSpacesRichList().isCurrentSortDescending(); - Collections.sort(nodes, new NodePropertyComparator(currentSortColumn, !currentSortDescending)); - previous = NodeListUtils.previousItem(nodes, id); - this.browseBean.setupSpaceAction(previous.getId(), false); - } - if (previous == null) - { - Node currNode = new Node(currNodeRef); - this.navigator.setupDispatchContext(currNode); - } - } - - } - - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_PREVIEW_OF) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) + getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/repository/DataDictionary.java b/war/src/main/java/org/alfresco/web/bean/repository/DataDictionary.java deleted file mode 100644 index a388480950..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/repository/DataDictionary.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.repository; - -import java.io.Serializable; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.service.cmr.dictionary.AssociationDefinition; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.cmr.dictionary.TypeDefinition; -import org.alfresco.service.namespace.QName; - -/** - * Lighweight client side representation of the repository data dictionary. - * This allows service calls to be kept to a minimum and for bean access, thus enabling JSF - * value binding expressions. - * - * @author gavinc - */ -public final class DataDictionary implements Serializable -{ - private static final long serialVersionUID = -4922351610793587592L; - - transient private DictionaryService dictionaryService; - private Map types = new HashMap(11, 1.0f); - - /** - * Constructor - * - * @param dictionaryService The dictionary service to use to retrieve the data - */ - public DataDictionary(DictionaryService dictionaryService) - { - this.dictionaryService = dictionaryService; - } - - /** - *@return dictionaryService - */ - public DictionaryService getDictionaryService() - { - //check for null for cluster environment - if (dictionaryService == null) - { - dictionaryService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getDictionaryService(); - } - return dictionaryService; - } - - /** - * Returns the type definition for the type represented by the given qname - * - * @param type The qname of the type to lookup the definition for - * @return The type definition for the requested type - */ - public TypeDefinition getTypeDef(QName type) - { - TypeDefinition typeDef = types.get(type); - - if (typeDef == null) - { - typeDef = getDictionaryService().getType(type); - - if (typeDef != null) - { - types.put(type, typeDef); - } - } - - return typeDef; - } - - /** - * Returns the type definition for the type represented by the given qname - * and for all the given aspects - * - * @param type The type to retrieve the definition for - * @param optionalAspects A list of aspects to retrieve the definition for - * @return A unified type definition of the given type and aspects - */ - public TypeDefinition getTypeDef(QName type, Collection optionalAspects) - { - return getDictionaryService().getAnonymousType(type, optionalAspects); - } - - /** - * Returns the property definition for the given property on the given node - * - * @param node The node from which to get the property - * @param property The property to find the definition for - * @return The property definition or null if the property is not known - */ - public PropertyDefinition getPropertyDefinition(Node node, String property) - { - PropertyDefinition propDef = null; - - TypeDefinition typeDef = getTypeDef(node.getType(), node.getAspects()); - - if (typeDef != null) - { - Map properties = typeDef.getProperties(); - propDef = properties.get(Repository.resolveToQName(property)); - } - - return propDef; - } - - /** - * Returns the association definition for the given association on the given node - * - * @param node The node from which to get the association - * @param association The association to find the definition for - * @return The association definition or null if the association is not known - */ - public AssociationDefinition getAssociationDefinition(Node node, String association) - { - AssociationDefinition assocDef = null; - - TypeDefinition typeDef = getTypeDef(node.getType(), node.getAspects()); - - if (typeDef != null) - { - Map assocs = typeDef.getAssociations(); - assocDef = assocs.get(Repository.resolveToQName(association)); - } - - return assocDef; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/repository/MapNode.java b/war/src/main/java/org/alfresco/web/bean/repository/MapNode.java deleted file mode 100644 index 88fa49337e..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/repository/MapNode.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.repository; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Map; -import java.util.Set; - -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.namespace.QName; - -/** - * Lighweight client side representation of a node held in the repository, which - * is modelled as a map for use in the data tables. - * - * @author gavinc - */ -public class MapNode extends Node implements Map -{ - private static final long serialVersionUID = 4051322327734433079L; - - private boolean propsInitialised = false; - - - /** - * Constructor - * - * @param nodeRef The NodeRef this Node wrapper represents - */ - public MapNode(NodeRef nodeRef) - { - super(nodeRef); - } - - /** - * Constructor - * - * @param nodeRef The NodeRef this Node wrapper represents - * @param nodeService The node service to use to retrieve data for this node - * @param initProps True to immediately init the properties of the node, false to do nothing - */ - public MapNode(NodeRef nodeRef, NodeService nodeService, boolean initProps) - { - super(nodeRef); - if (initProps == true) - { - getProperties(); - } - } - - /** - * Constructor - * - * @param nodeRef The NodeRef this Node wrapper represents - * @param nodeService The node service to use to retrieve data for this node - * @param props The properties of the node, already retrieved from NodeService - */ - public MapNode(NodeRef nodeRef, NodeService nodeService, Map props) - { - super(nodeRef); - - for (QName qname: props.keySet()) - { - Serializable propValue = props.get(qname); - this.properties.put(qname.toString(), propValue); - } - this.propsRetrieved = true; - } - - - // ------------------------------------------------------------------------------ - // Map implementation - allows the Node bean to be accessed using JSF expression syntax - - /** - * @see java.util.Map#clear() - */ - public void clear() - { - getProperties().clear(); - } - - /** - * @see java.util.Map#containsKey(java.lang.Object) - */ - public boolean containsKey(Object key) - { - return getProperties().containsKey(key); - } - - /** - * @see java.util.Map#containsValue(java.lang.Object) - */ - public boolean containsValue(Object value) - { - return getProperties().containsKey(value); - } - - /** - * @see java.util.Map#entrySet() - */ - public Set entrySet() - { - return getProperties().entrySet(); - } - - /** - * @see java.util.Map#get(java.lang.Object) - */ - public Object get(Object key) - { - Object obj = null; - - // there are some things that aren't available as properties - // but from method calls, so for these handle them individually - Map props = getProperties(); - if (propsInitialised == false) - { - // well known properties required as publically accessable map attributes - props.put("id", this.getId()); - props.put("name", this.getName()); // TODO: perf test pulling back single prop here instead of all! - props.put("nodeRef", this.getNodeRef()); - props.put("nodeRefAsString", this.getNodeRefAsString()); - - propsInitialised = true; - } - - if (key.equals("properties")) - { - return props; - } - else - { - return props.get(key); - } - } - - /** - * @see java.util.Map#isEmpty() - */ - public boolean isEmpty() - { - return getProperties().isEmpty(); - } - - /** - * @see java.util.Map#keySet() - */ - public Set keySet() - { - return getProperties().keySet(); - } - - /** - * @see java.util.Map#put(java.lang.Object, java.lang.Object) - */ - public Object put(String key, Object value) - { - return getProperties().put(key, value); - } - - /** - * @see java.util.Map#putAll(java.util.Map) - */ - public void putAll(Map t) - { - getProperties().putAll(t); - } - - /** - * @see java.util.Map#remove(java.lang.Object) - */ - public Object remove(Object key) - { - return getProperties().remove(key); - } - - /** - * @see java.util.Map#size() - */ - public int size() - { - return getProperties().size(); - } - - @Override - public void reset() - { - super.reset(); - propsInitialised = false; - } - - /** - * @see java.util.Map#values() - */ - public Collection values() - { - return getProperties().values(); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/repository/Node.java b/war/src/main/java/org/alfresco/web/bean/repository/Node.java deleted file mode 100644 index de50e3f2a3..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/repository/Node.java +++ /dev/null @@ -1,526 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.repository; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.lock.LockStatus; -import org.alfresco.service.cmr.repository.AssociationRef; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.Path; -import org.alfresco.service.cmr.security.AccessStatus; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.namespace.NamespacePrefixResolver; -import org.alfresco.service.namespace.NamespacePrefixResolverProvider; -import org.alfresco.service.namespace.QName; -import org.alfresco.service.namespace.RegexQNamePattern; -import org.alfresco.web.app.Application; - -/** - * Lighweight client side representation of a node held in the repository. - * - * @author gavinc - */ -public class Node implements Serializable, NamespacePrefixResolverProvider -{ - private static final long serialVersionUID = 3544390322739034170L; - - protected NodeRef nodeRef; - protected String name; - protected QName type; - protected Path path; - protected String id; - protected Set aspects = null; - protected Map permissions; - protected Boolean locked = null; - protected Boolean workingCopyOwner = null; - protected QNameNodeMap properties; - protected boolean propsRetrieved = false; - protected transient ServiceRegistry services = null; - protected boolean childAssocsRetrieved = false; - protected QNameNodeMap childAssociations; - protected boolean assocsRetrieved = false; - protected QNameNodeMap associations; - - private Map> childAssociationsAdded; - private Map> childAssociationsRemoved; - private Map> associationsAdded; - private Map> associationsRemoved; - - /** - * Constructor - * - * @param nodeRef The NodeRef this Node wrapper represents - */ - public Node(NodeRef nodeRef) - { - if (nodeRef == null) - { - throw new IllegalArgumentException("NodeRef must be supplied for creation of a Node."); - } - - this.nodeRef = nodeRef; - this.id = nodeRef.getId(); - - this.properties = new QNameNodeMap(this, this); - } - - /** - * @return All the properties known about this node. - */ - public Map getProperties() - { - if (this.propsRetrieved == false) - { - Map props = getServiceRegistry().getNodeService().getProperties(this.nodeRef); - - for (QName qname: props.keySet()) - { - Serializable propValue = props.get(qname); - - // Lists returned from the node service could be unmodifiable, - // therefore create copies for modification purposes - if (propValue instanceof List) - { - propValue = new ArrayList((List)propValue); - } - - this.properties.put(qname.toString(), propValue); - } - - this.propsRetrieved = true; - } - - return this.properties; - } - - /** - * @return All the associations this node has as a Map, using the association - * type as the key - */ - public final Map getAssociations() - { - if (this.assocsRetrieved == false) - { - this.associations = new QNameNodeMap(this, this); - - List assocs = getServiceRegistry().getNodeService().getTargetAssocs(this.nodeRef, RegexQNamePattern.MATCH_ALL); - - for (AssociationRef assocRef: assocs) - { - String assocName = assocRef.getTypeQName().toString(); - - List list = (List)this.associations.get(assocName); - // create the list if this is first association with 'assocName' - if (list == null) - { - list = new ArrayList(); - this.associations.put(assocName, list); - } - - // add the association to the list - list.add(assocRef); - } - - this.assocsRetrieved = true; - } - - return this.associations; - } - - /** - * Returns all the associations added to this node in this UI session - * - * @return Map of Maps of AssociationRefs - */ - public final Map> getAddedAssociations() - { - if (this.associationsAdded == null) - { - this.associationsAdded = new HashMap>(); - } - return this.associationsAdded; - } - - /** - * Returns all the associations removed from this node is this UI session - * - * @return Map of Maps of AssociationRefs - */ - public final Map> getRemovedAssociations() - { - if (this.associationsRemoved == null) - { - this.associationsRemoved = new HashMap>(); - } - return this.associationsRemoved; - } - - /** - * @return All the child associations this node has as a Map, using the association - * type as the key - */ - public final Map getChildAssociations() - { - if (this.childAssocsRetrieved == false) - { - this.childAssociations = new QNameNodeMap(this, this); - - List assocs = getServiceRegistry().getNodeService().getChildAssocs(this.nodeRef); - - for (ChildAssociationRef assocRef: assocs) - { - String assocName = assocRef.getTypeQName().toString(); - - List list = (List)this.childAssociations.get(assocName); - // create the list if this is first association with 'assocName' - if (list == null) - { - list = new ArrayList(); - this.childAssociations.put(assocName, list); - } - - // add the association to the list - list.add(assocRef); - } - - this.childAssocsRetrieved = true; - } - - return this.childAssociations; - } - - /** - * Returns all the child associations added to this node in this UI session - * - * @return Map of Maps of ChildAssociationRefs - */ - public final Map> getAddedChildAssociations() - { - if (this.childAssociationsAdded == null) - { - this.childAssociationsAdded = new HashMap>(); - } - return this.childAssociationsAdded; - } - - /** - * Returns all the child associations removed from this node is this UI session - * - * @return Map of Maps of ChildAssociationRefs - */ - public final Map> getRemovedChildAssociations() - { - if (this.childAssociationsRemoved == null) - { - this.childAssociationsRemoved = new HashMap>(); - } - return this.childAssociationsRemoved; - } - - /** - * Register a property resolver for the named property. - * - * @param name Name of the property this resolver is for - * @param resolver Property resolver to register - */ - public final void addPropertyResolver(String name, NodePropertyResolver resolver) - { - this.properties.addPropertyResolver(name, resolver); - } - - /** - * Returns if a property resolver with a specific name has been applied to the Node - * - * @param name of property resolver to look for - * - * @return true if a resolver with the name is found, false otherwise - */ - public final boolean containsPropertyResolver(String name) - { - return this.properties.containsPropertyResolver(name); - } - - /** - * Determines whether the given property name is held by this node - * - * @param propertyName Property to test existence of - * @return true if property exists, false otherwise - */ - public final boolean hasProperty(String propertyName) - { - return getProperties().containsKey(propertyName); - } - - /** - * @return Returns the NodeRef this Node object represents - */ - public final NodeRef getNodeRef() - { - return this.nodeRef; - } - - /** - * @return Returns the string form of the NodeRef this Node represents - */ - public final String getNodeRefAsString() - { - return this.nodeRef.toString(); - } - - /** - * @return Returns the type. - */ - public QName getType() - { - if (this.type == null) - { - this.type = getServiceRegistry().getNodeService().getType(this.nodeRef); - } - - return type; - } - - /** - * @return The display name for the node - */ - public String getName() - { - if (this.name == null) - { - // try and get the name from the properties first - this.name = (String)getProperties().get("cm:name"); - - // if we didn't find it as a property get the name from the association name - if (this.name == null) - { - this.name = getServiceRegistry().getNodeService().getPrimaryParent(this.nodeRef).getQName().getLocalName(); - } - } - - return this.name; - } - - /** - * @return The list of aspects applied to this node - */ - public final Set getAspects() - { - if (this.aspects == null) - { - this.aspects = getServiceRegistry().getNodeService().getAspects(this.nodeRef); - } - - return this.aspects; - } - - /** - * @param aspect The aspect to test for - * @return true if the node has the aspect false otherwise - */ - public final boolean hasAspect(QName aspect) - { - Set aspects = getAspects(); - return aspects.contains(aspect); - } - - /** - * Return whether the current user has the specified access permission on this Node - * - * @param permission Permission to validate against - * - * @return true if the permission is applied to the node for this user, false otherwise - */ - public boolean hasPermission(String permission) - { - Boolean valid = null; - if (this.permissions != null) - { - valid = this.permissions.get(permission); - } - else - { - this.permissions = new HashMap(8, 1.0f); - } - - if (valid == null) - { - PermissionService service = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPermissionService(); - valid = Boolean.valueOf(service.hasPermission(this.nodeRef, permission) == AccessStatus.ALLOWED); - this.permissions.put(permission, valid); - } - - return valid.booleanValue(); - } - - /** - * @return The GUID for the node - */ - public final String getId() - { - return this.id; - } - - /** - * @return The simple display path for the node - */ - public String getPath() - { - return getNodePath().toString(); - } - - /** - * @return the repo Path to the node - */ - public Path getNodePath() - { - if (this.path == null) - { - this.path = getServiceRegistry().getNodeService().getPath(this.nodeRef); - } - return this.path; - } - - /** - * @return If the node is currently locked - */ - public final boolean isLocked() - { - if (this.locked == null) - { - this.locked = Boolean.FALSE; - - if (hasAspect(ContentModel.ASPECT_LOCKABLE)) - { - locked = getServiceRegistry().getLockService().isLocked(getNodeRef()); - } - } - - return this.locked.booleanValue(); - } - - /** - * @return whether a the Node is a WorkingCopy owned by the current User - */ - public final boolean isWorkingCopyOwner() - { - if (this.workingCopyOwner == null) - { - this.workingCopyOwner = Boolean.FALSE; - - if (hasAspect(ContentModel.ASPECT_WORKING_COPY)) - { - Object obj = getProperties().get(ContentModel.PROP_WORKING_COPY_OWNER); - if (obj instanceof String) - { - User user = Application.getCurrentUser(FacesContext.getCurrentInstance()); - if ( ((String)obj).equals(user.getUserName())) - { - this.workingCopyOwner = Boolean.TRUE; - } - } - } - } - - return workingCopyOwner.booleanValue(); - } - - /** - * Resets the state of the node to force re-retrieval of the data - */ - public void reset() - { - this.name = null; - this.type = null; - this.path = null; - this.locked = null; - this.workingCopyOwner = null; - this.properties.clear(); - this.propsRetrieved = false; - this.aspects = null; - this.permissions = null; - - this.associations = null; - this.associationsAdded = null; - this.associationsRemoved = null; - this.assocsRetrieved = false; - - this.childAssociations = null; - this.childAssociationsAdded = null; - this.childAssociationsRemoved = null; - this.childAssocsRetrieved = false; - } - - /** - * Override Object.toString() to provide useful debug output - */ - public String toString() - { - if (getServiceRegistry().getNodeService() != null) - { - if (getServiceRegistry().getNodeService().exists(nodeRef)) - { - return "Node Type: " + getType() + - "\nNode Properties: " + this.getProperties().toString() + - "\nNode Aspects: " + this.getAspects().toString(); - } - else - { - return "Node no longer exists: " + nodeRef; - } - } - else - { - return super.toString(); - } - } - - protected ServiceRegistry getServiceRegistry() - { - if (this.services == null) - { - this.services = Repository.getServiceRegistry(FacesContext.getCurrentInstance()); - } - return this.services; - } - - public NamespacePrefixResolver getNamespacePrefixResolver() - { - return getServiceRegistry().getNamespaceService(); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/repository/NodePropertyResolver.java b/war/src/main/java/org/alfresco/web/bean/repository/NodePropertyResolver.java deleted file mode 100644 index 253f2c62a0..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/repository/NodePropertyResolver.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.repository; - -import java.io.Serializable; - -/** - * Simple interface used to implement small classes capable of calculating dynamic property values - * for Nodes at runtime. This allows bean responsible for building large lists of Nodes to - * encapsulate the code needed to retrieve non-standard Node properties. The values are then - * calculated on demand by the property resolver. - * - * When a node is reset() the standard and other props are cleared. If property resolvers are used - * then the non-standard props will be restored automatically as well. - * - * @author Kevin Roast - */ -public interface NodePropertyResolver extends Serializable -{ - /** - * Get the property value for this resolver - * - * @param node Node this property is for - * - * @return property value - */ - public Object get(Node node); -} diff --git a/war/src/main/java/org/alfresco/web/bean/repository/Preferences.java b/war/src/main/java/org/alfresco/web/bean/repository/Preferences.java deleted file mode 100644 index 12cb03a5ed..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/repository/Preferences.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.repository; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.transaction.UserTransaction; - -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; - -/** - * Wraps the notion of preferences and settings for a User. - * Caches values until they are overwritten with a new value. - * - * @author Kevin Roast - */ -public final class Preferences implements Serializable -{ - private static final long serialVersionUID = 722840612660970723L; - - private NodeRef preferencesRef; - private transient NodeService nodeService; - private Map cache = new HashMap(16, 1.0f); - - /** - * Package level constructor - */ - Preferences(NodeRef prefRef) - { - this.preferencesRef = prefRef; - } - - /** - * Get a serialized preferences value. - * - * @param name Name of the value to retrieve. - * - * @return The value or null if not found/set. - */ - public Serializable getValue(String name) - { - Serializable value = null; - - if (this.preferencesRef != null) - { - value = this.cache.get(name); - - if (value == null) - { - QName qname = QName.createQName(NamespaceService.APP_MODEL_1_0_URI, name); - value = getNodeService().getProperty(this.preferencesRef, qname); - this.cache.put(name, value); - } - } - - return value; - } - - /** - * Set a serialized preference value. - * - * @param name Name of the value to set. - * @param value Value to set. - */ - public void setValue(String name, Serializable value) - { - if (this.preferencesRef != null) - { - QName qname = QName.createQName(NamespaceService.APP_MODEL_1_0_URI, name); - - // persist the property to the repo - UserTransaction tx = null; - try - { - FacesContext context = FacesContext.getCurrentInstance(); - tx = Repository.getUserTransaction(context); - tx.begin(); - - getNodeService().setProperty(this.preferencesRef, qname, value); - - tx.commit(); - - // update the cache - this.cache.put(name, value); - } - catch (Throwable err) - { - // we cannot update the properties if a user is no longer authenticated - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - } - } - - /** - * @return the NodeService instance. - */ - private NodeService getNodeService() - { - if (this.nodeService == null) - { - this.nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - } - return this.nodeService; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/repository/PreferencesService.java b/war/src/main/java/org/alfresco/web/bean/repository/PreferencesService.java deleted file mode 100644 index 89a82671b9..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/repository/PreferencesService.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.repository; - -import javax.faces.context.FacesContext; -import javax.servlet.http.HttpSession; - -import org.alfresco.web.app.Application; - -/** - * Simple client service to retrieve the Preferences object for the current User. - * - * @author Kevin Roast - */ -public final class PreferencesService -{ - /** - * Private constructor - */ - private PreferencesService() - { - } - - /** - * @return The Preferences for the current User instance. - */ - public static Preferences getPreferences() - { - return getPreferences(FacesContext.getCurrentInstance()); - } - - /** - * @param fc FacesContext - * @return The Preferences for the current User instance. - */ - public static Preferences getPreferences(FacesContext fc) - { - User user = Application.getCurrentUser(fc); - return user != null ? user.getPreferences(fc) : null; - } - - /** - * @param session Http session - * @return The Preferences for the current User instance. - */ - public static Preferences getPreferences(HttpSession session) - { - User user = Application.getCurrentUser(session); - return user != null ? user.getPreferences(session.getServletContext()) : null; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/repository/QNameNodeMap.java b/war/src/main/java/org/alfresco/web/bean/repository/QNameNodeMap.java deleted file mode 100644 index 5dccb04f80..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/repository/QNameNodeMap.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.repository; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -import org.alfresco.service.namespace.NamespacePrefixResolverProvider; -import org.alfresco.service.namespace.QNameMap; - -/** - * A extension of the repo QNameMap to provide custom property resolving support for Node wrappers. - * - * @author Kevin Roast - */ -public final class QNameNodeMap extends QNameMap implements Map, Cloneable, Serializable -{ - private static final long serialVersionUID = -1760755862411509263L; - - private Node parent = null; - private Map resolvers = new HashMap(8, 1.0f); - - - /** - * Constructor - * - * @param parent Parent Node of the QNameNodeMap - */ - public QNameNodeMap(NamespacePrefixResolverProvider provider, Node parent) - { - super(provider); - if (parent == null) - { - throw new IllegalArgumentException("Parent Node cannot be null!"); - } - this.parent = parent; - } - - /** - * Serialization constructor - */ - protected QNameNodeMap() - { - super(); - } - - - /** - * Register a property resolver for the named property. - * - * @param name Name of the property this resolver is for - * @param resolver Property resolver to register - */ - public void addPropertyResolver(String name, NodePropertyResolver resolver) - { - this.resolvers.put(name, resolver); - } - - /** - * Returns if a property resolver with a specific name has been applied to the map - * - * @param name of property resolver to look for - * - * @return true if a resolver with the name is found, false otherwise - */ - public boolean containsPropertyResolver(String name) - { - return this.resolvers.containsKey(name); - } - - /** - * @see java.util.Map#containsKey(java.lang.Object) - */ - public boolean containsKey(Object key) - { - return (this.contents.containsKey(Repository.resolveToQNameString((String)key)) || - this.resolvers.containsKey(key)); - } - - /** - * @see java.util.Map#get(java.lang.Object) - */ - @SuppressWarnings("unchecked") - public Object get(Object key) - { - String qnameKey = Repository.resolveToQNameString(key.toString()); - Object obj = this.contents.get(qnameKey); - if (obj == null) - { - // if a property resolver exists for this property name then invoke it - NodePropertyResolver resolver = this.resolvers.get(key.toString()); - if (resolver != null) - { - obj = resolver.get(this.parent); - // cache the result - // obviously the cache is useless if the result is null, in most cases it shouldn't be - this.contents.put(qnameKey, obj); - } - } - - return obj; - } - - /** - * Perform a get without using property resolvers - * - * @param key item key - * @return object - */ - public Object getRaw(Object key) - { - return this.contents.get(Repository.resolveToQNameString((String)key)); - } - - /** - * Shallow copy the map by copying keys and values into a new QNameNodeMap - */ - @SuppressWarnings("unchecked") - public Object clone() - { - QNameNodeMap map = new QNameNodeMap(this.provider, this.parent); - map.putAll(this); - if (this.resolvers.size() != 0) - { - map.resolvers = (Map)((HashMap)this.resolvers).clone(); - } - return map; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/repository/Repository.java b/war/src/main/java/org/alfresco/web/bean/repository/Repository.java deleted file mode 100644 index 247331a6ce..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/repository/Repository.java +++ /dev/null @@ -1,883 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.repository; - -import java.io.File; -import java.io.InputStream; -import java.io.Serializable; -import java.nio.charset.Charset; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.servlet.ServletContext; -import javax.transaction.UserTransaction; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.configuration.ConfigurableService; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.repo.content.encoding.ContentCharsetFinder; -import org.alfresco.repo.content.filestore.FileContentReader; -import org.alfresco.repo.content.metadata.MetadataExtracter; -import org.alfresco.repo.content.metadata.MetadataExtracterRegistry; -import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork; -import org.alfresco.repo.tenant.TenantService; -import org.alfresco.repo.transaction.RetryingTransactionHelper; -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.lock.LockService; -import org.alfresco.service.cmr.lock.LockStatus; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.ContentReader; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.MimetypeService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.repository.Path; -import org.alfresco.service.cmr.repository.StoreRef; -import org.alfresco.service.cmr.search.SearchService; -import org.alfresco.service.cmr.security.AccessStatus; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.cmr.security.PersonService; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.service.transaction.TransactionService; -import org.alfresco.util.PathUtil; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.NavigationBean; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.IBreadcrumbHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.web.context.support.WebApplicationContextUtils; -import org.springframework.web.jsf.FacesContextUtils; - -/** - * Helper class for accessing repository objects, convert values, escape values and service utilities. - * - * @author gavinc - * @author kevinr - */ -public final class Repository -{ - /** I18N error messages */ - public static final String ERROR_NODEREF = "error_noderef"; - public static final String ERROR_GENERIC = "error_generic"; - public static final String ERROR_NOHOME = "error_homespace"; - public static final String ERROR_SEARCH = "error_search"; - public static final String ERROR_QUERY = "error_search_query"; - public static final String ERROR_EXISTS = "error_exists"; - - private static final String METADATA_EXTACTER_REGISTRY = "metadataExtracterRegistry"; - - private static Log logger = LogFactory.getLog(Repository.class); - - /** cache of client StoreRef */ - private static StoreRef storeRef = null; - - /** reference to the NamespaceService */ - private static NamespaceService namespaceService = null; - - /** reference to the ServiceRegistry */ - private static ServiceRegistry serviceRegistry = null; - - /** - * Private constructor - */ - private Repository() - { - } - - /** - * Returns a store reference object - * - * @return A StoreRef object - */ - public static StoreRef getStoreRef() - { - return storeRef; - } - - /** - * Returns a store reference object. - * This method is used to setup the cached value by the ContextListener initialisation methods - * - * @return The StoreRef object - */ - public static StoreRef getStoreRef(ServletContext context) - { - storeRef = Application.getRepositoryStoreRef(context); - - return storeRef; - } - - /** - * Returns a company root node reference object. - * - * @return The NodeRef object - */ - public static NodeRef getCompanyRoot(final FacesContext context) - { - final String currentUserName = Application.getCurrentUser(context).getUserName(); - - // note: run in context of System user using tenant-specific store - // so that Company Root can be returned, even if the user does not have - // permission to access the Company Root (including, for example, the Guest user) - return AuthenticationUtil.runAs(new RunAsWork() - { - public NodeRef doWork() throws Exception - { - ServiceRegistry sr = getServiceRegistry(context); - - TenantService tenantService = (TenantService)FacesContextUtils.getRequiredWebApplicationContext(context).getBean("tenantService"); - - // get store ref (from config) - StoreRef storeRef = tenantService.getName(currentUserName, Repository.getStoreRef()); - - // get root path (from config) - String rootPath = Application.getRootPath(context); - - return getCompanyRoot(sr.getNodeService(), sr.getSearchService(), sr.getNamespaceService(), storeRef, rootPath); - } - }, AuthenticationUtil.getSystemUserName()); - } - - /** - * Returns a company root node reference object. - * - * @return The NodeRef object - */ - public static NodeRef getCompanyRoot(NodeService nodeService, SearchService searchService, NamespaceService namespaceService, StoreRef storeRef, String rootPath) - { - // check the repository exists, create if it doesn't - if (nodeService.exists(storeRef) == false) - { - throw new AlfrescoRuntimeException("Store not created prior to application startup: " + storeRef); - } - - // get hold of the root node - NodeRef rootNodeRef = nodeService.getRootNode(storeRef); - - // see if the company home space is present - if (rootPath == null) - { - throw new AlfrescoRuntimeException("Root path has not been configured"); - } - - List nodes = searchService.selectNodes(rootNodeRef, rootPath, null, namespaceService, false); - if (nodes.size() == 0) - { - throw new AlfrescoRuntimeException("Root path not created prior to application startup: " + rootPath); - } - - // return company root - return nodes.get(0); - } - - /** - * Helper to get the display name for a Node. - * The method will attempt to use the "name" attribute, if not found it will revert to using - * the QName.getLocalName() retrieved from the primary parent relationship. - * - * @param ref NodeRef - * - * @return display name string for the specified Node. - */ - public static String getNameForNode(NodeService nodeService, NodeRef ref) - { - String name = null; - - // Check that node reference still exists - if (nodeService.exists(ref) == true) - { - // try to find a display "name" property for this node - Object nameProp = nodeService.getProperty(ref, ContentModel.PROP_NAME); - if (nameProp != null) - { - name = nameProp.toString(); - } - else - { - // revert to using QName if not found - QName qname = nodeService.getPrimaryParent(ref).getQName(); - if (qname != null) - { - name = qname.getLocalName(); - } - } - } - - return name; - } - - /** - * Helper to get the display name path for a category node. - * - * @param nodeService NodeService - * @param ref the category node ref - * @return display name string for the specified category node. - */ - public static String getNameForCategoryNode(NodeService nodeService, NodeRef ref) - { - String name = null; - - // Check that node reference still exists - if (nodeService.exists(ref) == true) - { - Path path = nodeService.getPath(ref); - name = Repository.getNamePath(nodeService, path, null, "/", null); - } - - return name; - } - - /** - * Escape a QName value so it can be used in lucene search strings - * - * @param qName QName to escape - * - * @return escaped value - */ - public static String escapeQName(QName qName) - { - String string = qName.toString(); - StringBuilder buf = new StringBuilder(string.length() + 4); - for (int i = 0; i < string.length(); i++) - { - char c = string.charAt(i); - if ((c == '{') || (c == '}') || (c == ':') || (c == '-')) - { - buf.append('\\'); - } - - buf.append(c); - } - return buf.toString(); - } - - /** - * Return whether a Node is currently locked - * - * @param node The Node wrapper to test against - * @param lockService The LockService to use - * - * @return whether a Node is currently locked - */ - public static Boolean isNodeLocked(Node node, LockService lockService) - { - Boolean locked = Boolean.FALSE; - - if (node.hasAspect(ContentModel.ASPECT_LOCKABLE)) - { - LockStatus lockStatus = lockService.getLockStatus(node.getNodeRef()); - if (lockStatus == LockStatus.LOCKED || lockStatus == LockStatus.LOCK_OWNER) - { - locked = Boolean.TRUE; - } - } - - return locked; - } - - /** - * Return whether a Node is currently locked by the current user - * - * @param node The Node wrapper to test against - * @param lockService The LockService to use - * - * @return whether a Node is currently locked by the current user - */ - public static Boolean isNodeOwnerLocked(Node node, LockService lockService) - { - Boolean locked = Boolean.FALSE; - - if (node.hasAspect(ContentModel.ASPECT_LOCKABLE) && - lockService.getLockStatus(node.getNodeRef()) == LockStatus.LOCK_OWNER) - { - locked = Boolean.TRUE; - } - - return locked; - } - - /** - * Return the human readable form of the specified node Path. Fast version of the method that - * simply converts QName localname components to Strings. - * - * @param path Path to extract readable form from, excluding the final element - * - * @return human readable form of the Path excluding the final element - */ - public static String getDisplayPath(Path path) - { - return getDisplayPath(path, false); - } - - /** - * Return the human readable form of the specified node Path. Fast version of the method that - * simply converts QName localname components to Strings. - * - * @param path Path to extract readable form from - * @param showLeaf Whether to process the final leaf element of the path - * - * @return human readable form of the Path excluding the final element - */ - public static String getDisplayPath(Path path, boolean showLeaf) - { - return PathUtil.getDisplayPath(path, showLeaf); - } - - /** - * Resolve a Path by converting each element into its display NAME attribute - * - * @param path Path to convert - * @param separator Separator to user between path elements - * @param prefix To prepend to the path - * - * @return Path converted using NAME attribute on each element - */ - public static String getNamePath(NodeService nodeService, Path path, NodeRef rootNode, String separator, String prefix) - { - StringBuilder buf = new StringBuilder(128); - - // ignore root node check if not passed in - boolean foundRoot = (rootNode == null); - - if (prefix != null) - { - buf.append(prefix); - } - - // skip first element as it represents repo root '/' - for (int i=1; i location, NodeRef node) - { - // make the sure the given list is empty - location.clear(); - - // get required services - NodeService nodeService = Repository.getServiceRegistry(context).getNodeService(); - DictionaryService dictionaryService = Repository.getServiceRegistry(context).getDictionaryService(); - PermissionService permsService = Repository.getServiceRegistry(context).getPermissionService(); - - // add the given node to start - String nodeName = Repository.getNameForNode(nodeService, node); - location.add(navBean.new NavigationBreadcrumbHandler(node, nodeName)); - - // get the given node's parent node - NodeRef parent = nodeService.getPrimaryParent(node).getParentRef(); - while (parent != null) - { - // check the user can read the parent node - if (permsService.hasPermission(parent, PermissionService.READ) == AccessStatus.ALLOWED) - { - // get the grand parent so we can check for the root node - NodeRef grandParent = nodeService.getPrimaryParent(parent).getParentRef(); - - if (grandParent != null) - { - // check that the node is actually a folder type, content can have children! - QName parentType = nodeService.getType(parent); - if (dictionaryService.isSubClass(parentType, ContentModel.TYPE_FOLDER)) - { - // if it's a folder add the location to the breadcrumb - String parentName = Repository.getNameForNode(nodeService, parent); - location.add(0, navBean.new NavigationBreadcrumbHandler(parent, parentName)); - } - } - - parent = grandParent; - } - else - { - // the user does not have Read permission above this point so stop! - break; - } - } - } - - /** - * Resolve a Path by converting each element into its display NAME attribute. - * Note: This method resolves path regardless access permissions. - * Fixes the UI part of the ETWOONE-214 and ETWOONE-238 issues - * - * @param path Path to convert - * @param separator Separator to user between path elements - * @param prefix To prepend to the path - * - * @return Path converted using NAME attribute on each element - */ - public static String getNamePathEx(FacesContext context, final Path path, final NodeRef rootNode, final String separator, final String prefix) - { - String result = null; - - RetryingTransactionHelper transactionHelper = getRetryingTransactionHelper(context); - transactionHelper.setMaxRetries(1); - final NodeService runtimeNodeService = (NodeService)FacesContextUtils.getRequiredWebApplicationContext(context).getBean("nodeService"); - result = transactionHelper.doInTransaction( - new RetryingTransactionCallback() - { - public String execute() throws Throwable - { - return getNamePath(runtimeNodeService, path, rootNode, separator, prefix); - } - }); - - return result; - } - - /** - * Return the mimetype for the specified file name. - *

- * The file extension will be extracted from the filename and used to lookup the mimetype. - * - * @param context FacesContext - * @param filename Non-null filename to process - * - * @return mimetype for the specified filename - falls back to 'application/octet-stream' if not found. - */ - public static String getMimeTypeForFileName(FacesContext context, String filename) - { - return getMimeTypeForFile(context, filename, null); - } - - /** - * Return the mimetype for the specified file, based on both the - * file name and the file's contents. - *

- * The file extension will be extracted from the filename and used - * along with the file contents to identify the mimetype. - * - * @param context FacesContext - * @param filename Non-null filename to process - * @param file The File object (used to read the contents) - * - * @return mimetype for the specified filename - falls back to 'application/octet-stream' if not found. - */ - public static String getMimeTypeForFile(FacesContext context, String filename, File file) - { - String mimetype = MimetypeMap.MIMETYPE_BINARY; - MimetypeService mimetypeService = (MimetypeService)getServiceRegistry(context).getMimetypeService(); - - // Use the file contents if available - if (file != null) - { - FileContentReader reader; - try - { - reader = new FileContentReader(file); - mimetype = mimetypeService.guessMimetype(filename, reader); - return mimetype; - } - catch (Throwable t) - { - // Not terminal - logger.warn("Error identifying mimetype from file contents ", t); - } - } - - // If the contents aren't available, go with the filename, - // falling back to the Binary Mimetype if needed - mimetype = mimetypeService.guessMimetype(filename); - return mimetype; - } - - /** - * Return a UserTransaction instance - * - * @param context FacesContext - * - * @return UserTransaction - * - * @deprecated - * @see #getRetryingTransactionHelper(FacesContext) - */ - public static UserTransaction getUserTransaction(FacesContext context) - { - TransactionService transactionService = getServiceRegistry(context).getTransactionService(); - return transactionService.getUserTransaction(); - } - - /** - * Returns the transaction helper that executes a unit of work. - * - * @param context FacesContext - * @return Returns the transaction helper - */ - public static RetryingTransactionHelper getRetryingTransactionHelper(FacesContext context) - { - TransactionService transactionService = getServiceRegistry(context).getTransactionService(); - return transactionService.getRetryingTransactionHelper(); - } - - /** - * Return a UserTransaction instance - * - * @param context FacesContext - * @param readonly Transaction readonly state - * - * @return UserTransaction - */ - public static UserTransaction getUserTransaction(FacesContext context, boolean readonly) - { - TransactionService transactionService = getServiceRegistry(context).getTransactionService(); - return transactionService.getUserTransaction(readonly); - } - - /** - * Return the Repository Service Registry - * - * @param context Faces Context - * @return the Service Registry - */ - public static ServiceRegistry getServiceRegistry(FacesContext context) - { - if (serviceRegistry == null) - { - serviceRegistry = (ServiceRegistry)FacesContextUtils.getRequiredWebApplicationContext( - context).getBean(ServiceRegistry.SERVICE_REGISTRY); - } - return serviceRegistry; - } - - /** - * Return the Repository Service Registry - * - * @param context Servlet Context - * @return the Service Registry - */ - public static ServiceRegistry getServiceRegistry(ServletContext context) - { - if (serviceRegistry == null) - { - serviceRegistry = (ServiceRegistry)WebApplicationContextUtils.getRequiredWebApplicationContext( - context).getBean(ServiceRegistry.SERVICE_REGISTRY); - } - return serviceRegistry; - } - - /** - * Return the Configurable Service - * - * @return the configurable service - */ - public static ConfigurableService getConfigurableService(FacesContext context) - { - return (ConfigurableService)FacesContextUtils.getRequiredWebApplicationContext(context).getBean("ConfigurableService"); - } - - /** - * Return the Metadata Extracter Registry - * - * @param context Faces Context - * @return the MetadataExtracterRegistry - */ - public static MetadataExtracterRegistry getMetadataExtracterRegistry(FacesContext context) - { - return (MetadataExtracterRegistry)FacesContextUtils.getRequiredWebApplicationContext( - context).getBean(METADATA_EXTACTER_REGISTRY); - } - - /** - * Extracts the metadata of a "raw" piece of content into a map. - * - * @param context Faces Context - * @param reader Content reader for the source content to extract from - * @param destination Map of metadata to set metadata values into - * @return True if an extracter was found - */ - public static boolean extractMetadata(FacesContext context, ContentReader reader, Map destination) - { - // check that source mimetype is available - String mimetype = reader.getMimetype(); - if (mimetype == null) - { - throw new AlfrescoRuntimeException("The content reader mimetype must be set: " + reader); - } - - // look for a transformer - MetadataExtracter extracter = getMetadataExtracterRegistry(context).getExtracter(mimetype); - if (extracter == null) - { - // No metadata extracter is not a failure, but we flag it - return false; - } - - try - { - // we have a transformer, so do it - extracter.extract(reader, destination); - return true; - } - catch (Throwable e) - { - // it failed - logger.warn("Metadata extraction failed: \n" + - " reader: " + reader + "\n" + - " extracter: " + extracter); - return false; - } - } - - /** - * Extract the characterset from the stream - * - * @param context the Faces Context - * @param is the stream of characters or data - * @param mimetype the stream's mimetype, or null if unknown - * @return Returns the guessed characterset and never null - */ - public static String guessEncoding(FacesContext context, InputStream is, String mimetype) - { - ContentCharsetFinder charsetFinder = getServiceRegistry(context).getMimetypeService().getContentCharsetFinder(); - Charset charset = charsetFinder.getCharset(is, mimetype); - return charset.name(); - } - - /** - * Query a list of Person type nodes from the repo - * It is currently assumed that all Person nodes exist below the Repository root node - * - * @param context Faces Context - * @param nodeService The node service - * @param searchService The search service, which is ignored - * @return List of Person node objects - * @deprecated Use {@link #getUsers(FacesContext, NodeService, PersonService)} instead - */ - public static List getUsers(FacesContext context, NodeService nodeService, SearchService searchService) - { - PersonService personService = (PersonService)FacesContextUtils.getRequiredWebApplicationContext(context).getBean("personService"); - return getUsers(context, nodeService, personService); - } - - /** - * Query a list of Person type nodes from the repo - * It is currently assumed that all Person nodes exist below the Repository root node - * - * @param context Faces Context - * @param nodeService The node service - * @param personService PersonService - * @return List of Person node objects - */ - public static List getUsers(FacesContext context, NodeService nodeService, PersonService personService) - { - List personNodes = null; - - UserTransaction tx = null; - try - { - tx = Repository.getUserTransaction(context, true); - tx.begin(); - - NodeRef peopleRef = personService.getPeopleContainer(); - - // TODO: better to perform an XPath search or a get for a specific child type here? - List childRefs = nodeService.getChildAssocs(peopleRef); - personNodes = new ArrayList(childRefs.size()); - for (ChildAssociationRef ref: childRefs) - { - // create our Node representation from the NodeRef - NodeRef nodeRef = ref.getChildRef(); - - if (nodeService.getType(nodeRef).equals(ContentModel.TYPE_PERSON)) - { - // create our Node representation - MapNode node = new MapNode(nodeRef); - - // set data binding properties - // this will also force initialisation of the props now during the UserTransaction - // it is much better for performance to do this now rather than during page bind - Map props = node.getProperties(); - String firstName = (String)props.get("firstName"); - String lastName = (String)props.get("lastName"); - props.put("fullName", (firstName != null ? firstName : "") + ' ' + (lastName != null ? lastName : "")); - NodeRef homeFolderNodeRef = (NodeRef)props.get("homeFolder"); - if (homeFolderNodeRef != null) - { - props.put("homeSpace", homeFolderNodeRef); - } - - personNodes.add(node); - } - } - - // commit the transaction - tx.commit(); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - context, Repository.ERROR_NODEREF), new Object[] {"root"}) ); - personNodes = Collections.emptyList(); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - context, Repository.ERROR_GENERIC), err.getMessage()), err ); - personNodes = Collections.emptyList(); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - - return personNodes; - } - - /** - * @return true if we are currently the special Guest user - */ - public static boolean getIsGuest(FacesContext context) - { - TenantService tenantService = (TenantService)FacesContextUtils.getRequiredWebApplicationContext(context).getBean("tenantService"); - String userName = Application.getCurrentUser(context).getUserName(); - return tenantService.getBaseNameUser(userName).equalsIgnoreCase(AuthenticationUtil.getGuestUserName()); - } - - /** - * Convert a property of unknown type to a String value. A native String value will be - * returned directly, else toString() will be executed, null is returned as null. - * - * @param value Property value - * - * @return value to String or null - */ - public static String safePropertyToString(Serializable value) - { - if (value == null) - { - return null; - } - else if (value instanceof String) - { - return (String)value; - } - else - { - return value.toString(); - } - } - - /** - * Creates a QName representation for the given String. - * If the String has no namespace the Alfresco namespace is added. - * If the String has a prefix an attempt to resolve the prefix to the - * full URI will be made. - * - * @param str The string to convert - * @return A QName representation of the given string - */ - public static QName resolveToQName(String str) - { - return QName.resolveToQName(getNamespaceService(), str); - } - - /** - * Creates a string representation of a QName for the given string. - * If the given string already has a namespace, either a URL or a prefix, - * nothing the given string is returned. If it does not have a namespace - * the Alfresco namespace is added. - * - * @param str The string to convert - * @return A QName String representation of the given string - */ - public static String resolveToQNameString(String str) - { - return QName.resolveToQNameString(getNamespaceService(), str); - } - - /** - * Returns an instance of the namespace service - * - * @return The NamespaceService - */ - private static NamespaceService getNamespaceService() - { - if (namespaceService == null) - { - ServiceRegistry svcReg = getServiceRegistry(FacesContext.getCurrentInstance()); - namespaceService = svcReg.getNamespaceService(); - } - - return namespaceService; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/repository/TransientMapNode.java b/war/src/main/java/org/alfresco/web/bean/repository/TransientMapNode.java deleted file mode 100644 index bd82802a3e..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/repository/TransientMapNode.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.repository; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Map; -import java.util.Set; - -import org.alfresco.service.namespace.QName; - -/** - * Represents a transient node i.e. it is not and will not be present in the repository. - *

- * This type of node is typically used to drive rich lists where the Map implementation - * is required for sorting columns. - *

- * - * @author gavinc - */ -public class TransientMapNode extends TransientNode implements Map -{ - private static final long serialVersionUID = 1120307465342597322L; - - /** - * Constructor. - *

- * NOTE: The name is NOT automatically added to the map of properties, - * if you need the name of this node to be in the map then add it to - * the map passed in to this constructor. - *

- * - * @param type The type this node will represent - * @param name The name of the node - * @param data The properties and associations this node will have - */ - public TransientMapNode(QName type, String name, Map data) - { - super(type, name, data); - } - - @Override - public String toString() - { - return "Transient map node of type: " + getType() + - "\nProperties: " + this.getProperties().toString(); - } - - // ------------------------------------------------------------------------------ - // Map implementation - allows the Node bean to be accessed using JSF expression syntax - - /** - * @see java.util.Map#clear() - */ - public void clear() - { - getProperties().clear(); - } - - /** - * @see java.util.Map#containsKey(java.lang.Object) - */ - public boolean containsKey(Object key) - { - return getProperties().containsKey(key); - } - - /** - * @see java.util.Map#containsValue(java.lang.Object) - */ - public boolean containsValue(Object value) - { - return getProperties().containsKey(value); - } - - /** - * @see java.util.Map#entrySet() - */ - @SuppressWarnings("unchecked") - public Set entrySet() - { - return getProperties().entrySet(); - } - - /** - * @see java.util.Map#get(java.lang.Object) - */ - public Object get(Object key) - { - return getProperties().get(key); - } - - /** - * @see java.util.Map#isEmpty() - */ - public boolean isEmpty() - { - return getProperties().isEmpty(); - } - - /** - * @see java.util.Map#keySet() - */ - @SuppressWarnings("unchecked") - public Set keySet() - { - return getProperties().keySet(); - } - - /** - * @see java.util.Map#put(java.lang.Object, java.lang.Object) - */ - public Object put(String key, Object value) - { - return getProperties().put(key, value); - } - - /** - * @see java.util.Map#putAll(java.util.Map) - */ - @SuppressWarnings("unchecked") - public void putAll(Map t) - { - getProperties().putAll(t); - } - - /** - * @see java.util.Map#remove(java.lang.Object) - */ - public Object remove(Object key) - { - return getProperties().remove(key); - } - - /** - * @see java.util.Map#size() - */ - public int size() - { - return getProperties().size(); - } - - /** - * @see java.util.Map#values() - */ - @SuppressWarnings("unchecked") - public Collection values() - { - return getProperties().values(); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/repository/TransientNode.java b/war/src/main/java/org/alfresco/web/bean/repository/TransientNode.java deleted file mode 100644 index 3a88e7aed3..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/repository/TransientNode.java +++ /dev/null @@ -1,313 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.repository; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.service.cmr.dictionary.AspectDefinition; -import org.alfresco.service.cmr.dictionary.AssociationDefinition; -import org.alfresco.service.cmr.dictionary.ClassDefinition; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.cmr.dictionary.TypeDefinition; -import org.alfresco.service.cmr.repository.AssociationRef; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter; -import org.alfresco.service.namespace.QName; -import org.alfresco.util.GUID; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Represents a transient node i.e. it is not and will not be present in the repository. - *

- * This type of node is typically used to drive the property sheet when data collection - * is required for a type but the node does not need to be stored in the repository. An - * example use is the workflow, transient nodes are used to collect workitem metadata. - *

- * - * @author gavinc - */ -public class TransientNode extends Node -{ - private static final long serialVersionUID = 2140554155948154106L; - - private static final Log logger = LogFactory.getLog(TransientNode.class); - - /** - * Constructor. - *

- * NOTE: The name is NOT automatically added to the map of properties, - * if you need the name of this node to be in the map then add it to - * the map passed in to this constructor. - *

- * - * @param type The type this node will represent - * @param name The name of the node - * @param data The properties and associations this node will have - */ - public TransientNode(QName type, String name, Map data) - { - // create a dummy NodeRef to pass to the constructor - super(new NodeRef(Repository.getStoreRef(), GUID.generate())); - - this.type = type; - this.name = name; - - // initialise the node - initNode(data); - } - - /** - * Construct a transient node for an item yet to be created in the Repository. - * - * This will apply any one-time initialisation required upon creation of the node - * e.g. assignment of default values. - * - * @param dictionaryService dictionary service - * @param typeDef The type definition this node will represent - * @param name The name of the node - * @param data The properties and associations this node will have - * @return transient node - */ - public static TransientNode createNew(DictionaryService dictionaryService, TypeDefinition typeDef, String name, Map data) - { - // build a complete anonymous type for the start task - List aspects = typeDef.getDefaultAspects(); - List aspectNames = new ArrayList(aspects.size()); - getMandatoryAspects(typeDef, aspectNames); - ClassDefinition startTaskDef = dictionaryService.getAnonymousType(typeDef.getName(), aspectNames); - - // initialise start task values - Map startValues = new HashMap(); - if (data != null) - { - startValues.putAll(data); - } - - // apply default values - Map propertyDefs = startTaskDef.getProperties(); - for (Map.Entry entry : propertyDefs.entrySet()) - { - String defaultValue = entry.getValue().getDefaultValue(); - if (defaultValue != null) - { - if (startValues.get(entry.getKey()) == null) - { - startValues.put(entry.getKey(), (Serializable)DefaultTypeConverter.INSTANCE.convert(entry.getValue().getDataType(), defaultValue)); - } - } - } - - return new TransientNode(typeDef.getName(), name, startValues); - } - - /** - * Gets a flattened list of all mandatory aspects for a given class - * - * @param classDef the class - * @param aspects a list to hold the mandatory aspects - */ - private static void getMandatoryAspects(ClassDefinition classDef, List aspects) - { - for (AspectDefinition aspect : classDef.getDefaultAspects()) - { - QName aspectName = aspect.getName(); - if (!aspects.contains(aspectName)) - { - aspects.add(aspect.getName()); - getMandatoryAspects(aspect, aspects); - } - } - } - - /** - * Initialises the node. - * - * @param data The properties and associations to initialise the node with - */ - protected void initNode(Map data) - { - // setup the transient node so that the super class methods work - // and do not need to go back to the repository - - if (logger.isDebugEnabled()) - logger.debug("Initialising transient node with data: " + data); - - DictionaryService ddService = this.getServiceRegistry().getDictionaryService(); - - // marshall the given properties and associations into the internal maps - this.associations = new QNameNodeMap(this, this); - this.childAssociations = new QNameNodeMap(this, this); - - if (data != null) - { - // go through all data items and allocate to the correct internal list - for (QName item : data.keySet()) - { - PropertyDefinition propDef = ddService.getProperty(item); - if (propDef != null) - { - this.properties.put(item, data.get(item)); - } - else - { - // see if the item is either type of association - AssociationDefinition assocDef = ddService.getAssociation(item); - if (assocDef != null) - { - if (assocDef.isChild()) - { - Object obj = data.get(item); - if (obj instanceof NodeRef) - { - NodeRef child = (NodeRef)obj; - - // create a child association reference, add it to a list and add the list - // to the list of child associations for this node - List assocs = new ArrayList(1); - ChildAssociationRef childRef = new ChildAssociationRef(assocDef.getName(), this.nodeRef, - null, child); - assocs.add(childRef); - - this.childAssociations.put(item, assocs); - } - else if (obj instanceof List) - { - List targets = (List)obj; - - List assocs = new ArrayList(targets.size()); - - for (Object target : targets) - { - if (target instanceof NodeRef) - { - NodeRef currentChild = (NodeRef)target; - ChildAssociationRef childRef = new ChildAssociationRef(assocDef.getName(), - this.nodeRef, null, currentChild); - assocs.add(childRef); - } - } - - if (assocs.size() > 0) - { - this.childAssociations.put(item, assocs); - } - } - } - else - { - Object obj = data.get(item); - if (obj instanceof NodeRef) - { - NodeRef target = (NodeRef)obj; - - // create a association reference, add it to a list and add the list - // to the list of associations for this node - List assocs = new ArrayList(1); - AssociationRef assocRef = new AssociationRef(null, this.nodeRef, assocDef.getName(), target); - assocs.add(assocRef); - - this.associations.put(item, assocs); - } - else if (obj instanceof List) - { - List targets = (List)obj; - - List assocs = new ArrayList(targets.size()); - - for (Object target : targets) - { - if (target instanceof NodeRef) - { - NodeRef currentTarget = (NodeRef)target; - AssociationRef assocRef = new AssociationRef(null, this.nodeRef, assocDef.getName(), currentTarget); - assocs.add(assocRef); - } - } - - if (assocs.size() > 0) - { - this.associations.put(item, assocs); - } - } - } - } - } - } - } - - // show that the maps have been initialised - this.propsRetrieved = true; - this.assocsRetrieved = true; - this.childAssocsRetrieved = true; - - // setup the list of aspects the node would have - TypeDefinition typeDef = ddService.getType(this.type); - if (typeDef == null) - { - throw new AlfrescoRuntimeException("Failed to find type definition: " + this.type); - } - - // get flat list of all aspects for the type - List defaultAspects = new ArrayList(16); - getMandatoryAspects(typeDef, defaultAspects); - - this.aspects = new HashSet(defaultAspects); - - // setup remaining variables - this.path = null; - this.locked = Boolean.FALSE; - this.workingCopyOwner = Boolean.FALSE; - } - - @Override - public boolean hasPermission(String permission) - { - return true; - } - - @Override - public void reset() - { - // don't reset anything otherwise we'll lose our data - // with no way of getting it back!! - } - - @Override - public String toString() - { - return "Transient node of type: " + getType() + - "\nProperties: " + this.getProperties().toString(); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/repository/User.java b/war/src/main/java/org/alfresco/web/bean/repository/User.java deleted file mode 100644 index 622b894683..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/repository/User.java +++ /dev/null @@ -1,328 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.repository; - -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.servlet.ServletContext; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.SessionUser; -import org.alfresco.repo.configuration.ConfigurableService; -import org.alfresco.repo.transaction.RetryingTransactionHelper; -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.search.SearchService; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.service.transaction.TransactionService; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.WebApplicationContextUtils; -import org.springframework.web.jsf.FacesContextUtils; - -/** - * Bean that represents the currently logged in user - * - * @author gavinc - */ -public final class User implements SessionUser -{ - private static final long serialVersionUID = -90577901805847829L; - - private String companyRootId; - private String homeSpaceId; - private String userName; - private String ticket; - private NodeRef person; - private String fullName = null; - private Boolean administrator = null; - - private Preferences preferences = null; - - /** - * Constructor - * - * @param userName constructor for the user - */ - public User(String userName, String ticket, NodeRef person) - { - if (userName == null || ticket == null || person == null) - { - throw new IllegalArgumentException("All user details are mandatory!"); - } - - this.userName = userName; - this.ticket = ticket; - this.person = person; - } - - /** - * Forces a clear of any cached or calcluated values - */ - public void reset() - { - this.fullName = null; - this.administrator = null; - this.preferences = null; - } - - /** - * @return The user name - */ - public String getUserName() - { - return this.userName; - } - - /** - * Return the full name of the Person this User represents - * - * @param service NodeService to use - * - * @return The full name - */ - public String getFullName(NodeService service) - { - if (this.fullName == null) - { - String firstName = (String)service.getProperty(this.person, ContentModel.PROP_FIRSTNAME); - String lastName = (String)service.getProperty(this.person, ContentModel.PROP_LASTNAME); - this.fullName = (firstName != null ? firstName : "") + ' ' + (lastName != null ? lastName : ""); - } - - return this.fullName; - } - - /** - * @return Retrieves the user's home space (this may be the id of the company home space) - */ - public String getHomeSpaceId() - { - return this.homeSpaceId; - } - - /** - * @param homeSpaceId Sets the id of the users home space - */ - public void setHomeSpaceId(String homeSpaceId) - { - this.homeSpaceId = homeSpaceId; - } - - /** - * @return Retrieves the company home space - */ - public String getCompanyRootId() - { - return this.companyRootId; - } - - /** - * @param companyRootId Sets the id of the company home space - */ - public void setCompanyRootId(String companyRootId) - { - this.companyRootId = companyRootId; - } - - /** - * @return Returns the ticket. - */ - public String getTicket() - { - return this.ticket; - } - - /** - * @return Returns the person NodeRef - */ - public NodeRef getPerson() - { - return this.person; - } - - /** - * @return If the current user has Admin Authority - */ - public boolean isAdmin() - { - if (administrator == null) - { - administrator = Repository.getServiceRegistry(FacesContext.getCurrentInstance()) - .getAuthorityService().hasAdminAuthority(); - } - - return administrator; - } - - /** - * @return The Preferences for the User - */ - Preferences getPreferences(FacesContext fc) - { - if (this.preferences == null) - { - this.preferences = new Preferences(getUserPreferencesRef( - FacesContextUtils.getRequiredWebApplicationContext(fc))); - } - return this.preferences; - } - - /** - * @return The Preferences for the User - */ - Preferences getPreferences(ServletContext sc) - { - if (this.preferences == null) - { - this.preferences = new Preferences(getUserPreferencesRef( - WebApplicationContextUtils.getRequiredWebApplicationContext(sc))); - } - return this.preferences; - } - - /** - * Get or create the node used to store user preferences. - * Utilises the 'configurable' aspect on the Person linked to this user. - */ - synchronized NodeRef getUserPreferencesRef(WebApplicationContext context) - { - final ServiceRegistry registry = (ServiceRegistry) context.getBean("ServiceRegistry"); - final NodeService nodeService = registry.getNodeService(); - final SearchService searchService = registry.getSearchService(); - final NamespaceService namespaceService = registry.getNamespaceService(); - final TransactionService txService = registry.getTransactionService(); - final ConfigurableService configurableService = (ConfigurableService) context.getBean("ConfigurableService"); - RetryingTransactionHelper txnHelper = registry.getTransactionService().getRetryingTransactionHelper(); - return txnHelper.doInTransaction(new RetryingTransactionCallback() - { - public NodeRef execute() throws Throwable - { - NodeRef prefRef = null; - NodeRef person = getPerson(); - if (nodeService.hasAspect(person, ApplicationModel.ASPECT_CONFIGURABLE) == false) - { - // if the repository is in read-only mode just return null - if (txService.isReadOnly()) - { - return null; - } - else - { - // create the configuration folder for this Person node - configurableService.makeConfigurable(person); - } - } - - // target of the assoc is the configurations folder ref - NodeRef configRef = configurableService.getConfigurationFolder(person); - if (configRef == null) - { - throw new IllegalStateException("Unable to find associated 'configurations' folder for node: " - + person); - } - - String xpath = NamespaceService.APP_MODEL_PREFIX + ":" + "preferences"; - List nodes = searchService.selectNodes(configRef, xpath, null, namespaceService, false); - - if (nodes.size() == 1) - { - prefRef = nodes.get(0); - } - else - { - // create the preferences Node for this user (if repo is not read-only) - if (txService.isReadOnly() == false) - { - ChildAssociationRef childRef = nodeService.createNode(configRef, - ContentModel.ASSOC_CONTAINS, QName.createQName( - NamespaceService.APP_MODEL_1_0_URI, "preferences"), - ContentModel.TYPE_CMOBJECT); - - prefRef = childRef.getChildRef(); - } - } - return prefRef; - } - }, txService.isReadOnly()); - } - - /** - * Returns the full name of the user represented by the given NodeRef - * - * @param nodeService The node service instance - * @param user The user to get the full name for - * @return The full name - */ - public static String getFullName(NodeService nodeService, NodeRef user) - { - Map props = nodeService.getProperties(user); - String firstName = (String)props.get(ContentModel.PROP_FIRSTNAME); - String lastName = (String)props.get(ContentModel.PROP_LASTNAME); - String fullName = firstName + ((lastName != null && lastName.length() > 0) ? " " + lastName : ""); - - return fullName; - } - - /** - * Returns the full name of the user plus their userid in the form [id] - * - * @param nodeService The node service instance - * @param user The user to get the full name for - * @return The full name and userid - */ - public static String getFullNameAndUserId(NodeService nodeService, NodeRef user) - { - String fullName = getFullName(nodeService, user); - String userId = (String)nodeService.getProperties(user).get(ContentModel.PROP_USERNAME); - - StringBuilder nameAndId = new StringBuilder(); - if (fullName != null && fullName.length() > 0 && fullName.equals("null") == false) - { - nameAndId.append(fullName); - nameAndId.append(" "); - } - - nameAndId.append("["); - nameAndId.append(userId); - nameAndId.append("]"); - - return nameAndId.toString(); - } - - @Override - public String toString() - { - return this.userName; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/repository/admin/RepoAdminConsoleBean.java b/war/src/main/java/org/alfresco/web/bean/repository/admin/RepoAdminConsoleBean.java deleted file mode 100644 index 9d3ea498df..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/repository/admin/RepoAdminConsoleBean.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.repository.admin; - -import java.io.PrintWriter; -import java.io.Serializable; -import java.io.StringWriter; - -import javax.faces.context.FacesContext; - -import org.alfresco.repo.admin.RepoAdminInterpreter; -import org.alfresco.web.app.servlet.FacesHelper; - - -/** - * Backing bean to support the Repository Admin Console - */ -public class RepoAdminConsoleBean implements Serializable -{ - private static final long serialVersionUID = -8131607149189675180L; - - // command - private String command = ""; - private String submittedCommand = "none"; - private long duration = 0L; - private String result = null; - - // supporting repository services - transient private RepoAdminInterpreter repoAdminInterpreter; - - - /** - * @param repoAdminInterpreter repo admin interpreter - */ - public void setRepoAdminInterpreter(RepoAdminInterpreter repoAdminInterpreter) - { - this.repoAdminInterpreter = repoAdminInterpreter; - } - - /** - *@return repoAdminInterpreter - */ - private RepoAdminInterpreter getRepoAdminInterpreter() - { - //check for null for cluster environment - if (repoAdminInterpreter == null) - { - repoAdminInterpreter = (RepoAdminInterpreter) FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), "repoAdminInterpreter"); - } - return repoAdminInterpreter; - } - - /** - * Gets the command result - * - * @return result - */ - public String getResult() - { - if (result == null) - { - interpretCommand("help"); - } - return result; - } - - /** - * Sets the command result - * - * @param result String - */ - public void setResult(String result) - { - this.result = result; - } - - /** - * Gets the current query - * - * @return query statement - */ - public String getCommand() - { - return command; - } - - /** - * Set the current command - * - * @param command command - */ - public void setCommand(String command) - { - this.command = command; - } - - /** - * Gets the submitted command - * - * @return submitted command - */ - public String getSubmittedCommand() - { - return submittedCommand; - } - - /** - * Set the submitted command - * - * @param submittedCommand The submitted command - */ - public void setSubmittedCommand(String submittedCommand) - { - this.submittedCommand = submittedCommand; - } - - /** - * Gets the last command duration - * - * @return command duration - */ - public long getDuration() - { - return duration; - } - - /** - * Set the duration - * - * @param duration The duration - */ - public void setDuration(long duration) - { - this.duration = duration; - } - - /** - * Action to submit command - * - * @return next action - */ - public String submitCommand() - { - interpretCommand(command); - return "success"; - } - - /** - * Gets the current user name - * - * @return user name - */ - public String getCurrentUserName() - { - return getRepoAdminInterpreter().getCurrentUserName(); - } - - /** - * Interpret repo admin console command - * - * @param command command - */ - private void interpretCommand(String command) - { - try - { - long startms = System.currentTimeMillis(); - String result = getRepoAdminInterpreter().interpretCommand(command); - setDuration(System.currentTimeMillis() - startms); - setResult(result); - setCommand(""); - setSubmittedCommand(command); - } - catch (Exception e) - { - StringWriter stackTrace = new StringWriter(); - e.printStackTrace(new PrintWriter(stackTrace)); - setResult(stackTrace.toString()); - } - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/repository/tenant/TenantAdminConsoleBean.java b/war/src/main/java/org/alfresco/web/bean/repository/tenant/TenantAdminConsoleBean.java deleted file mode 100644 index 699f5043ce..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/repository/tenant/TenantAdminConsoleBean.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.repository.tenant; - -import java.io.PrintWriter; -import java.io.Serializable; -import java.io.StringWriter; - -import javax.faces.context.FacesContext; - -import org.alfresco.repo.tenant.TenantInterpreter; -import org.alfresco.web.app.servlet.FacesHelper; - - -/** - * Backing bean to support the Tenant Admin Console - */ -public class TenantAdminConsoleBean implements Serializable -{ - private static final long serialVersionUID = -9116623180660597894L; - - // command - private String command = ""; - private String submittedCommand = "none"; - private long duration = 0L; - private String result = null; - - // supporting repository services - transient private TenantInterpreter tenantInterpreter; - - - /** - * @param tenantInterpreter tenant admin interpreter - */ - public void setTenantInterpreter(TenantInterpreter tenantInterpreter) - { - this.tenantInterpreter = tenantInterpreter; - } - - /** - * @return tenantInterpreter - */ - private TenantInterpreter geTenantInterpreter() - { - //check for null for cluster environment - if (tenantInterpreter == null) - { - tenantInterpreter = (TenantInterpreter) FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), "tenantInterpreter"); - } - return tenantInterpreter; - } - - /** - * Gets the command result - * - * @return result - */ - public String getResult() - { - if (result == null) - { - interpretCommand("help"); - } - return result; - } - - /** - * Sets the command result - * - * @param result String - */ - public void setResult(String result) - { - this.result = result; - } - - /** - * Gets the current query - * - * @return query statement - */ - public String getCommand() - { - return command; - } - - /** - * Set the current command - * - * @param command command - */ - public void setCommand(String command) - { - this.command = command; - } - - /** - * Gets the submitted command - * - * @return submitted command - */ - public String getSubmittedCommand() - { - return submittedCommand; - } - - /** - * Set the submitted command - * - * @param submittedCommand The submitted command - */ - public void setSubmittedCommand(String submittedCommand) - { - this.submittedCommand = submittedCommand; - } - - /** - * Gets the last command duration - * - * @return command duration - */ - public long getDuration() - { - return duration; - } - - /** - * Set the duration - * - * @param duration The duration - */ - public void setDuration(long duration) - { - this.duration = duration; - } - - /** - * Action to submit command - * - * @return next action - */ - public String submitCommand() - { - interpretCommand(command); - return "success"; - } - - /** - * Gets the current user name - * - * @return user name - */ - public String getCurrentUserName() - { - return (geTenantInterpreter() != null) ? geTenantInterpreter().getCurrentUserName() : null; - } - - /** - * Interpret tenant admin console command - * - * @param command command - */ - private void interpretCommand(String command) - { - try - { - long startms = System.currentTimeMillis(); - String result = (geTenantInterpreter() != null) ? geTenantInterpreter().interpretCommand(command) : "Tenant AdminConsole is not available - check that multi-tenancy is enabled !"; - setDuration(System.currentTimeMillis() - startms); - setResult(result); - setCommand(""); - setSubmittedCommand(command); - } - catch (Exception e) - { - StringWriter stackTrace = new StringWriter(); - e.printStackTrace(new PrintWriter(stackTrace)); - setResult(stackTrace.toString()); - } - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/rules/CreateCompositeRuleWizard.java b/war/src/main/java/org/alfresco/web/bean/rules/CreateCompositeRuleWizard.java deleted file mode 100644 index f76d8e62c8..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/rules/CreateCompositeRuleWizard.java +++ /dev/null @@ -1,452 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.rules; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.model.DataModel; -import javax.faces.model.ListDataModel; -import javax.faces.model.SelectItem; - -import org.springframework.extensions.config.Config; -import org.springframework.extensions.config.ConfigService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.actions.IHandler; -import org.alfresco.web.bean.rules.handlers.BaseConditionHandler; -import org.alfresco.web.bean.rules.handlers.CompositeConditionHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class CreateCompositeRuleWizard extends CreateRuleWizard -{ - private static final Log logger = LogFactory.getLog(CreateCompositeRuleWizard.class); - - private List compositeConditions; - - // Right now the UI only supports one level of recursion, although the - // backend supports unlimited recursion for composites. - // This limitation is introduced by the fact that we are have two "current" - // conditions - either normal condition, or composite conditions - // basically, the UI will have to store conditions in a more native way - // (instead of DataModel) to get unlimited number of composite conditions recursing - protected DataModel currentCompositeConditionsDataModel; - protected List> currentCompositeConditionPropertiesList; - - private boolean addingCompositeCondition; - private boolean editCurrentCompositeCondition; - - private int rowIndex = -1; - - - public CreateCompositeRuleWizard() - { - } - - @Override - public void init(Map parameters) - { - super.init(parameters); - - this.setAddingCompositeCondition(false); - this.currentCompositeConditionsDataModel = null; - this.currentCompositeConditionPropertiesList = null; - } - - public void setupCompositeConditionsMode() - { - this.setAddingCompositeCondition(true); - this.currentCompositeConditionsDataModel = new ListDataModel(); - this.currentCompositeConditionPropertiesList = new ArrayList>(); - } - - private void clearCompositeConditionMode() - { - // reset the action drop down - this.selectedCondition = null; - // this.currentConditionProperties = null; - this.currentCompositeConditionsDataModel = null; - this.currentCompositeConditionPropertiesList = null; - this.setAddingCompositeCondition(false); - } - - /** - * Returns the properties for all the conditions as a JSF DataModel - * - * @return JSF DataModel representing the condition properties - */ - public DataModel getAllCompositeConditionsDataModel() - { - if (this.currentCompositeConditionsDataModel == null) - { - this.currentCompositeConditionsDataModel = new ListDataModel(); - } - - this.currentCompositeConditionsDataModel.setWrappedData(this.currentCompositeConditionPropertiesList); - - return this.currentCompositeConditionsDataModel; - } - - /** - * Displays the settings page for the current condition being added (if - * required) - */ - @Override - public void promptForConditionValues() - { - if (CompositeConditionHandler.NAME.equals(this.selectedCondition)) - { - setupCompositeConditionsMode(); - } - - super.promptForConditionValues(); - } - - public void finishAddingCompositeCondition() - { - if (logger.isDebugEnabled()) - logger.debug("Finishing Adding Composite Condition."); - - // reset the effective chosen condition to composite-condition - this.selectedCondition = CompositeConditionHandler.NAME; - - FacesContext context = FacesContext.getCurrentInstance(); - returnViewId = getWizardContainerViewId(context); - - printConditionState(); - - if (logger.isDebugEnabled()) - logger.debug("\tAdding Condition '" + selectedCondition + "'"); - - IHandler handler = this.conditionHandlers.get(this.selectedCondition); - - // creating object temporarily so we can pass it to CompositeConditionHandler - currentConditionProperties.put(CompositeConditionHandler.PROP_COMPOSITE_CONDITION, - (Serializable) this.currentCompositeConditionPropertiesList); - currentConditionProperties.put(PROP_CONDITION_NAME, this.selectedCondition); - - // this is called from the actions page so there must be a handler - // present so there's no need to check for null - String summary = handler.generateSummary(context, this, currentConditionProperties); - - if (summary != null) - { - currentConditionProperties.put(PROP_CONDITION_SUMMARY, summary); - } - if (logger.isDebugEnabled()) - logger.debug("Generated Summary - [" + summary + "] + selectedCondition " + this.selectedCondition); - - if (this.editCurrentCompositeCondition == true) - { - if (rowIndex != -1) - { - this.allConditionsPropertiesList.remove(rowIndex); - this.allConditionsPropertiesList.add(rowIndex, currentConditionProperties); - } - } - else - { - this.allConditionsPropertiesList.add(currentConditionProperties); - } - - this.editCurrentCompositeCondition = false; - this.rowIndex = -1; - clearCompositeConditionMode(); - // refresh the wizard - goToPage(context, this.returnViewId); - } - - private String getWizardContainerViewId(FacesContext context) - { - String viewId = null; - ConfigService configSvc = Application.getConfigService(context); - Config globalConfig = configSvc.getGlobalConfig(); - if (globalConfig != null) - { - viewId = globalConfig.getConfigElement("wizard-container").getValue(); - } - else - { - logger.error("plain-dialog-container configuraion setting is not found"); - } - return viewId; - } - - @Override - public void cancelAddCondition() - { - this.editCurrentCompositeCondition = false; - this.rowIndex = -1; - if (isAddingCompositeCondition()) - { - // don't clear when editing, since we are looking at a REFERENCE to an existing condition - if (this.editingCondition == false) - { - this.currentConditionProperties.clear(); - } - - // reset the action drop down - this.selectedCondition = null; - - // determine what page to go back to - FacesContext context = FacesContext.getCurrentInstance(); - String currentViewId = context.getViewRoot().getViewId(); - - IHandler handler = this.conditionHandlers.get(CompositeConditionHandler.NAME); - String compositePage = handler.getJSPPath(); - - if (currentViewId.equals(compositePage)) - { - this.returnViewId = getWizardContainerViewId(context); - } - - goToPage(FacesContext.getCurrentInstance(), this.returnViewId); - } - else - { - super.cancelAddCondition(); - return; - } - } - - /** - * Adds the condition just setup by the user to the list of composite - * conditions This gathers the composite conditions in the - */ - @Override - public void addCondition() - { - if (!isAddingCompositeCondition()) - { - super.addCondition(); - printConditionState(); - return; - } - - if (logger.isDebugEnabled()) - logger.debug("Adding Condition to Composite Condition. "); - - FacesContext context = FacesContext.getCurrentInstance(); - - // this is called from the actions page so there must be a handler - // present so there's no need to check for null - IHandler handler = this.conditionHandlers.get(this.selectedCondition); - - if (handler != null) - { - String summary = handler.generateSummary(context, this, this.currentConditionProperties); - this.currentConditionProperties.put(PROP_CONDITION_SUMMARY, summary); - } - else - { - if (logger.isWarnEnabled()) - logger.warn("No Summary could be generated for rule condition " + this.selectedCondition); - - this.currentConditionProperties.put(PROP_CONDITION_SUMMARY, "ERROR - No Summary for " + this.selectedCondition); - } - - if (editingCondition == false) - { - //this check is needed to prevent an condition when you are editing a composite, to prevent it from adding twice - currentCompositeConditionPropertiesList.add(this.currentConditionProperties); - if (logger.isDebugEnabled()) - logger.debug("\tAdded condition to Composite condition."); - } - else - { - if (logger.isDebugEnabled()) - logger.debug("\tEdited composite condition. "); - } - - this.currentConditionProperties = new HashMap(3); - - // resetting it for composite condition - // TODO: this is not persistent currently, which causes a minor bug - this.currentConditionProperties.put(PROP_CONDITION_NAME, CompositeConditionHandler.NAME); - this.currentConditionProperties.put(BaseConditionHandler.PROP_CONDITION_NOT, Boolean.FALSE); - - // reset the action drop down - this.selectedCondition = null; - - // refresh the wizard - printConditionState(); - goToPage(context, this.returnViewId); - } - - /** - * Sets up the context for editing existing composite condition values - */ - @SuppressWarnings("unchecked") - public void editCondition() - { - this.editingCondition = true; - - if (logger.isDebugEnabled()) - logger.debug("Editing Conditions. isAddingCompositeConditions - " + isAddingCompositeCondition()); - - //if user is on main conditions screen, check if the condition to be edited is a composite condition - if (!isAddingCompositeCondition()) - { - Map condition = (Map) this.allConditionsDataModel.getRowData(); - this.rowIndex = this.allConditionsDataModel.getRowIndex(); - this.editCurrentCompositeCondition = true; - - if (condition.get(PROP_CONDITION_NAME).equals(CompositeConditionHandler.NAME)) - { - logger.debug("Composite Condition selected, enabling CompositeCondition Mode"); - currentCompositeConditionPropertiesList = (List>) condition - .get(CompositeConditionHandler.PROP_COMPOSITE_CONDITION); - addingCompositeCondition = true; - } - super.editCondition(condition ); - return; - } - else - { - Map subCondition = (Map) currentCompositeConditionsDataModel.getRowData(); - super.editCondition(subCondition); - } - } - - public List getCompositeConditions() - { - if (this.compositeConditions == null) - { - this.compositeConditions = new ArrayList(); - List tempConditions = this.getConditions(); // loads up the conditions - for (SelectItem item : tempConditions) - { - if (!((item.getValue().equals(CompositeConditionHandler.NAME)) || (item.getValue().equals("no-condition")))) - { - this.compositeConditions.add(item); - } - } - } - - return this.compositeConditions; - } - - protected boolean isAddingCompositeCondition() - { - return addingCompositeCondition; - } - - protected void setAddingCompositeCondition(boolean addingCompositeCondition) - { - if (logger.isDebugEnabled()) - logger.debug("Setting addingCompositeCondition to " + addingCompositeCondition); - - this.addingCompositeCondition = addingCompositeCondition; - } - - /** - * Removes the requested condition from the list - */ - public void removeCondition() - { - if (!isAddingCompositeCondition()) - { - super.removeCondition(); - return; - } - - if (logger.isDebugEnabled()) - logger.debug("Removing Composite Conditions"); - - // use the built in JSF support for retrieving the object for the - // row that was clicked by the user - Map conditionToRemove = (Map) this.currentCompositeConditionsDataModel.getRowData(); - this.currentCompositeConditionPropertiesList.remove(conditionToRemove); - // reset the action drop down - this.selectedCondition = null; - - // refresh the wizard - FacesContext context = FacesContext.getCurrentInstance(); - goToPage(context, context.getViewRoot().getViewId()); - } - - protected void printConditionState() - { - if (logger.isDebugEnabled()) - { - logger.debug("\t\t*** GLOBAL ***"); - - logger.debug("\t\tallConditionsProperties"); - if (allConditionsPropertiesList == null) - { - logger.debug("\t\t\tempty"); - } - else - { - for (Object obj : allConditionsPropertiesList) - { - logger.debug("\t\t\t" + obj.toString()); - } - } - - logger.debug("\t\t*** COMPOSITE ***"); - logger.debug("\t\taddingCompositeCondition " + addingCompositeCondition); - - logger.debug("\t\tcurrentCompositeConditionsProperties"); - if (currentCompositeConditionPropertiesList == null) - { - logger.debug("\t\t\t EMPTY"); - } - else - { - int i = 1; - for (Map cond : currentCompositeConditionPropertiesList) - { - logger.debug("\t\t\tCondition" + i++); - - for (String key : cond.keySet()) - { - logger.debug("\t\t\t\tkey - {" + key + "} value - {" + cond.get(key) + "}"); - } - } - } - - logger.debug("\t\t*** BOTH ***"); - - logger.debug("\t\tcurrentConditionsProperties"); - if (currentConditionProperties == null) - { - logger.debug("\t\t\t EMPTY"); - } - else - { - for (String key : this.currentConditionProperties.keySet()) - { - logger.debug("\t\t\tkey - {" + key + "} value - {" + this.currentConditionProperties.get(key) + "}"); - } - } - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/rules/CreateRuleWizard.java b/war/src/main/java/org/alfresco/web/bean/rules/CreateRuleWizard.java deleted file mode 100644 index d90c6f4ee9..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/rules/CreateRuleWizard.java +++ /dev/null @@ -1,952 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.rules; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.ResourceBundle; - -import javax.faces.context.FacesContext; -import javax.faces.model.DataModel; -import javax.faces.model.ListDataModel; -import javax.faces.model.SelectItem; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.service.cmr.action.Action; -import org.alfresco.service.cmr.action.ActionCondition; -import org.alfresco.service.cmr.action.ActionConditionDefinition; -import org.alfresco.service.cmr.action.CompositeAction; -import org.alfresco.service.cmr.action.CompositeActionCondition; -import org.alfresco.service.cmr.dictionary.TypeDefinition; -import org.alfresco.service.cmr.rule.Rule; -import org.alfresco.service.cmr.rule.RuleService; -import org.alfresco.service.cmr.rule.RuleType; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.actions.BaseActionWizard; -import org.alfresco.web.bean.actions.IHandler; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.rules.handlers.BaseConditionHandler; -import org.alfresco.web.bean.rules.handlers.CompositeConditionHandler; -import org.alfresco.web.data.IDataContainer; -import org.alfresco.web.data.QuickSort; -import org.alfresco.web.ui.common.Utils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.extensions.config.Config; -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigService; - -/** - * Bean implementation for the "Create Rule" wizard - * - * @author gavinc - */ -public class CreateRuleWizard extends BaseActionWizard -{ - private static final long serialVersionUID = 6197875728665281192L; - - protected static final String PROP_CONDITION_NAME = "conditionName"; - protected static final String PROP_CONDITION_SUMMARY = "conditionSummary"; - - private static final String RULE_OUTBOUND = "outbound"; - private static final String ACTION_CHECK_OUT = "check-out"; - - transient private RuleService ruleService; - protected RulesDialog rulesDialog; - - private List modelTypes; //this is for subtype condition - private List mimeTypes; //for checking mime types condition - private List types; - - private List conditions; - - protected Map conditionHandlers; //contains UI handlers, i.e. classes that know which JSP to to forward to - - //This is where all the current condition properties go. When addConditions is called, - //these are saved into allConditionsPropertiesList - protected Map currentConditionProperties; - - transient protected DataModel allConditionsDataModel; - - // protected List> allConditionsProperties; - //allConditionsProperties needs to be able to store both Map and List> - //(for composite conditions) - protected List> allConditionsPropertiesList; - - protected String title; - protected String description; - protected String type; - protected String selectedCondition; - protected boolean runInBackground; - protected boolean applyToSubSpaces; - protected boolean editingCondition; - protected boolean ruleDisabled; - - private static final Log logger = LogFactory.getLog(CreateRuleWizard.class); - - // ------------------------------------------------------------------------------ - // Wizard implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - this.title = null; - this.description = null; - this.type = "inbound"; - this.selectedCondition = null; - this.applyToSubSpaces = false; - this.runInBackground = false; - this.ruleDisabled = false; - this.conditions = null; - - this.allConditionsPropertiesList = new ArrayList>(); - - initialiseConditionHandlers(); - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - if (logger.isDebugEnabled()) - logger.debug("finishImpl called - saving rules"); - - // get hold of the space the rule will apply to and make sure - // it is actionable - Node currentSpace = this.browseBean.getActionSpace(); - - // create the new rule - //Rule rule = this.ruleService.createRule(this.getType()); - Rule rule = new Rule(); - rule.setRuleType(this.getType()); - - // setup the rule - outcome = setupRule(context, rule, outcome); - - // Save the rule - this.getRuleService().saveRule(currentSpace.getNodeRef(), rule); - - if (logger.isDebugEnabled()) - logger.debug("Added rule '" + this.title + "'"); - - return outcome; - } - - @Override - public boolean getNextButtonDisabled() - { - // TODO: Allow the next button state to be configured so that - // wizard implementations don't have to worry about - // checking step numbers - - boolean disabled = true; - int step = Application.getWizardManager().getCurrentStep(); - switch (step) - { - case 1: - { - disabled = (this.allConditionsDataModel == null || this.allConditionsDataModel.getRowCount() == 0); - break; - } - case 2: - { - disabled = (this.allActionsDataModel == null || this.allActionsDataModel.getRowCount() == 0); - break; - } - case 3: - { - disabled = (this.title == null || this.title.length() == 0); - break; - } - } - - return disabled; - } - - @Override - public boolean getFinishButtonDisabled() - { - if (this.allActionsDataModel != null && this.allActionsDataModel.getRowCount() > 0 - && this.allConditionsDataModel != null && this.allConditionsDataModel.getRowCount() > 0 - && this.title != null && this.title.length() > 0) - { - return false; - } - else - { - return true; - } - } - - /** - * @return Returns the summary data for the wizard. - */ - public String getSummary() - { - // create the summary using all the conditions - StringBuilder conditionsSummary = new StringBuilder(); - for (Map props : this.allConditionsPropertiesList) - { - conditionsSummary.append(Utils.encode((String)props.get(PROP_CONDITION_SUMMARY))); - conditionsSummary.append("
"); - } - - // create the summary using all the actions - StringBuilder actionsSummary = new StringBuilder(); - for (Map props : this.allActionsProperties) - { - actionsSummary.append(Utils.encode((String)props.get(PROP_ACTION_SUMMARY))); - actionsSummary.append("
"); - } - - ResourceBundle bundle = Application.getBundle(FacesContext.getCurrentInstance()); - - String backgroundYesNo = this.runInBackground ? bundle.getString("yes") : bundle.getString("no"); - String subSpacesYesNo = this.applyToSubSpaces ? bundle.getString("yes") : bundle.getString("no"); - String ruleDisabledYesNo = this.ruleDisabled ? bundle.getString("yes") : bundle.getString("no"); - - return buildSummary(new String[] - { bundle.getString("rule_type"), bundle.getString("name"), bundle.getString("description"), - bundle.getString("apply_to_sub_spaces"), bundle.getString("run_in_background"), - bundle.getString("rule_disabled"), bundle.getString("conditions"), bundle.getString("actions") }, - new String[] - { this.type, Utils.encode(this.title), Utils.encode(this.description), subSpacesYesNo, backgroundYesNo, - ruleDisabledYesNo, conditionsSummary.toString(), actionsSummary.toString() }); - } - - @Override - protected String getErrorMessageId() - { - return "error_rule"; - } - - protected CompositeAction getCompositeAction(Rule rule) - { - // Get the composite action - Action ruleAction = rule.getAction(); - if (ruleAction == null) - { - throw new AlfrescoRuntimeException("Rule does not have associated action."); - } - else if ((ruleAction instanceof CompositeAction) == false) - { - throw new AlfrescoRuntimeException("Rules with non-composite actions are not currently supported by the UI"); - } - return (CompositeAction) ruleAction; - } - - // ------------------------------------------------------------------------------ - // Bean Getters and Setters - - /** - * Determines whether the rule type drop down list should be enabled. - * - * @return false as the rule type drop down should be enabled - */ - public boolean getRuleTypeDisabled() - { - return false; - } - - /** - * Returns the properties for all the conditions as a JSF DataModel - * - * @return JSF DataModel representing the condition properties - */ - public DataModel getAllConditionsDataModel() - { - if (this.allConditionsDataModel == null) - { - this.allConditionsDataModel = new ListDataModel(); - } - - this.allConditionsDataModel.setWrappedData(this.allConditionsPropertiesList); - - return this.allConditionsDataModel; - } - - /** - * Returns a list of the types available in the repository - * - * @return List of SelectItem objects - */ - public List getModelTypes() - { - if ((this.modelTypes == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - FacesContext context = FacesContext.getCurrentInstance(); - ConfigService svc = Application.getConfigService(context); - Config wizardCfg = svc.getConfig("Action Wizards"); - if (wizardCfg != null) - { - ConfigElement typesCfg = wizardCfg.getConfigElement("subtypes"); - if (typesCfg != null) - { - this.modelTypes = new ArrayList(); - for (ConfigElement child : typesCfg.getChildren()) - { - QName idQName = Repository.resolveToQName(child.getAttribute("name")); - - // get the display label from config - String label = Utils.getDisplayLabel(context, child); - - // if there wasn't a client based label try and get it from the dictionary - if (label == null) - { - TypeDefinition typeDef = this.getDictionaryService().getType(idQName); - if (typeDef != null) - { - label = typeDef.getTitle(this.getDictionaryService()); - } - else - { - label = idQName.getLocalName(); - } - } - - this.modelTypes.add(new SelectItem(idQName.toString(), label)); - } - - // make sure the list is sorted by the label - QuickSort sorter = new QuickSort(this.modelTypes, "label", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - } - else - { - logger.warn("Could not find 'subtypes' configuration element"); - } - } - else - { - logger.warn("Could not find 'Action Wizards' configuration section"); - } - } - - return this.modelTypes; - } - - /** - * Returns a list of mime types in the system - * - * @return List of mime types - */ - public List getMimeTypes() - { - if (this.mimeTypes == null) - { - this.mimeTypes = new ArrayList(50); - - Map mimeTypes = getMimetypeService().getDisplaysByMimetype(); - for (String mimeType : mimeTypes.keySet()) - { - this.mimeTypes.add(new SelectItem(mimeType, mimeTypes.get(mimeType))); - } - - // make sure the list is sorted by the values - QuickSort sorter = new QuickSort(this.mimeTypes, "label", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - } - - return this.mimeTypes; - } - - /** - * @return Returns the list of selectable conditions - */ - public List getConditions() - { - if (this.conditions == null) - { - List ruleConditions = this.getActionService().getActionConditionDefinitions(); - this.conditions = new ArrayList(ruleConditions.size()); - for (ActionConditionDefinition ruleConditionDef : ruleConditions) - { - // add to SelectItem list - this.conditions.add(new SelectItem(ruleConditionDef.getName(), ruleConditionDef.getTitle())); - } - - // make sure the list is sorted by the label - QuickSort sorter = new QuickSort(this.conditions, "label", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - - // add the "Select a condition" entry at the beginning of the list - this.conditions.add(0, new SelectItem("null", Application.getMessage(FacesContext.getCurrentInstance(), - "select_a_condition"))); - } - - return this.conditions; - } - - /** - * @return Returns the types of rules that can be defined - */ - public List getTypes() - { - if (this.types == null) - { - List ruleTypes = this.getRuleService().getRuleTypes(); - this.types = new ArrayList(ruleTypes.size()); - for (RuleType ruleType : ruleTypes) - { - this.types.add(new SelectItem(ruleType.getName(), ruleType.getDisplayLabel())); - } - } - - return shouldFilterTypes() ? filterTypes(this.types) : this.types; - } - - private boolean shouldFilterTypes() - { - boolean filter = false; - - for (Map actionProperty: this.allActionsProperties) - { - if (actionProperty.get(PROP_ACTION_NAME).toString().equalsIgnoreCase(ACTION_CHECK_OUT)) - { - filter = true; - break; - } - } - - return filter; - } - - private List filterTypes(List types) - { - List filteredTypes = new ArrayList(types); - for (Iterator iterator = filteredTypes.iterator(); iterator.hasNext();) - { - SelectItem selectItem = iterator.next(); - if (selectItem.getValue().toString().equalsIgnoreCase(RULE_OUTBOUND)) - { - iterator.remove(); - } - } - - return filteredTypes; - } - - /** - * @return Gets the condition settings - */ - public Map getConditionProperties() - { - return this.currentConditionProperties; - } - - /** - * @return Returns the description. - */ - public String getDescription() - { - return description; - } - - /** - * @param description The description to set. - */ - public void setDescription(String description) - { - this.description = description; - } - - /** - * @return Returns the title. - */ - public String getTitle() - { - return title; - } - - /** - * @param title The title to set. - */ - public void setTitle(String title) - { - this.title = title; - } - - /** - * @return Returns whether the rule should run in the background - */ - public boolean getRunInBackground() - { - return this.runInBackground; - } - - /** - * @param runInBackground Sets whether the rule should run in the background - */ - public void setRunInBackground(boolean runInBackground) - { - this.runInBackground = runInBackground; - } - - /** - * @return Returns whether the rule should be applied to sub spaces i.e. if it gets inherited - */ - public boolean getApplyToSubSpaces() - { - return this.applyToSubSpaces; - } - - /** - * @param applyToSubSpaces Sets whether the rule will get applied to sub spaces - */ - public void setApplyToSubSpaces(boolean applyToSubSpaces) - { - this.applyToSubSpaces = applyToSubSpaces; - } - - /** - * @return Returns whether the rule is disabled or not. - */ - public boolean getRuleDisabled() - { - return this.ruleDisabled; - } - - /** - * @param ruleDisabled Sets whether the rule is disabled or not - */ - public void setRuleDisabled(boolean ruleDisabled) - { - this.ruleDisabled = ruleDisabled; - } - - /** - * @return Returns the type. - */ - public String getType() - { - return type; - } - - /** - * @param type The type to set - */ - public void setType(String type) - { - this.type = type; - } - - /** - * @return Returns the selected condition - */ - public String getCondition() - { - return this.selectedCondition; - } - - /** - * @param condition Sets the selected condition - */ - public void setCondition(String condition) - { - this.selectedCondition = condition; - } - - - // ------------------------------------------------------------------------------ - // Action event handlers - - /** - * Displays the settings page for the current condition being added (if required) - */ - public void promptForConditionValues() - { - // set the flag to show we are creating a new condition - this.editingCondition = false; - - FacesContext context = FacesContext.getCurrentInstance(); - this.returnViewId = context.getViewRoot().getViewId(); - String viewId = null; - - this.currentConditionProperties = new HashMap(3); - this.currentConditionProperties.put(PROP_CONDITION_NAME, this.selectedCondition); - this.currentConditionProperties.put(BaseConditionHandler.PROP_CONDITION_NOT, Boolean.FALSE); - - // get the handler for the condition, if there isn't one we presume it - // is a no-parameter condition - IHandler handler = this.conditionHandlers.get(this.selectedCondition); - if (handler != null) - { - if (logger.isDebugEnabled()) - logger.debug("Found Handler for selected condition - '" + this.selectedCondition + "'"); - - // setup any UI defaults the condition may have and get the location of - // the JSP used to collect the parameters - handler.setupUIDefaults(this.currentConditionProperties); - viewId = handler.getJSPPath(); - if (logger.isDebugEnabled()) - logger.debug("Handler returned JSP page- '" + viewId + "' Handler Type " + handler.getClass().toString()); - } - else - { - if (logger.isDebugEnabled()) - logger.debug("Did Not Find a handler for selected condition - '" + this.selectedCondition + "'"); - - // just add the action to the list and use the title as the summary - ActionConditionDefinition conditionDef = this.getActionService() - .getActionConditionDefinition(this.selectedCondition); - this.currentConditionProperties.put(PROP_CONDITION_SUMMARY, conditionDef.getTitle()); - this.currentConditionProperties.put(BaseConditionHandler.PROP_CONDITION_NOT, Boolean.FALSE); - // add the no params marker so we can disable the edit action - this.currentConditionProperties.put(NO_PARAMS_MARKER, "no-params"); - this.allConditionsPropertiesList.add(this.currentConditionProperties); - - // come back to the same page we're on now as there are no params to collect - viewId = this.returnViewId; - } - - if (logger.isDebugEnabled()) - logger.debug("Currently creating '" + this.selectedCondition + "' condition"); - - // go to the page to collect the settings - goToPage(context, viewId); - } - - /** - * Sets up the context for editing existing condition values - */ - @SuppressWarnings("unchecked") - public void editCondition() - { - Map conditionToEdit = (Map) this.allConditionsDataModel.getRowData(); - editCondition(conditionToEdit); - } - - protected void editCondition(Map conditionToEdit) - { - // set the flag to show we are editing a condition - this.editingCondition = true; - - // use the built in JSF support for retrieving the object for the - // row that was clicked by the user - this.selectedCondition = (String) conditionToEdit.get(PROP_CONDITION_NAME); - this.currentConditionProperties = conditionToEdit; - - if (logger.isDebugEnabled()) - logger.debug("Editing Condition '" + selectedCondition + "'"); - - // remember the page we're on - FacesContext context = FacesContext.getCurrentInstance(); - this.returnViewId = context.getViewRoot().getViewId(); - - // go to the condition page (as there is an edit option visible, - // there must be a handler for the condition so we don't check) - goToPage(context, this.conditionHandlers.get(this.selectedCondition).getJSPPath()); - } - - /** - * Adds the condition just setup by the user to the list of conditions for the rule - */ - public void addCondition() - { - FacesContext context = FacesContext.getCurrentInstance(); - - if (logger.isDebugEnabled()) - logger.debug("Adding Condition '" + selectedCondition + "'"); - - IHandler handler = this.conditionHandlers.get(this.selectedCondition); - - // this is called from the actions page so there must be a handler - // present so there's no need to check for null - String summary = handler.generateSummary(context, this, this.currentConditionProperties); - - if (summary != null) - { - this.currentConditionProperties.put(PROP_CONDITION_SUMMARY, summary); - } - if (logger.isDebugEnabled()) - logger.debug("Generated Summary - [" + summary + "] + selectedCondition " + this.selectedCondition); - - if (this.editingCondition == false) - { - this.allConditionsPropertiesList.add(this.currentConditionProperties); - - } - - // reset the action drop down - this.selectedCondition = null; - - // refresh the wizard - goToPage(context, this.returnViewId); - } - - /** - * Removes the requested condition from the list - */ - public void removeCondition() - { - // use the built in JSF support for retrieving the object for the - // row that was clicked by the user - Map conditionToRemove = (Map) this.allConditionsDataModel.getRowData(); - this.allConditionsPropertiesList.remove(conditionToRemove); - - // reset the action drop down - this.selectedCondition = null; - - // refresh the wizard - FacesContext context = FacesContext.getCurrentInstance(); - goToPage(context, context.getViewRoot().getViewId()); - } - - /** - * Cancels the addition of the condition - */ - public void cancelAddCondition() - { - if (this.editingCondition == false) - { - this.currentConditionProperties.clear(); - } - - // reset the action drop down - this.selectedCondition = null; - - // refresh the wizard - goToPage(FacesContext.getCurrentInstance(), this.returnViewId); - } - - - // ------------------------------------------------------------------------------ - // Service Injection - - /** - * @param ruleService Sets the rule service to use - */ - public void setRuleService(RuleService ruleService) - { - this.ruleService = ruleService; - } - - protected RuleService getRuleService() - { - if (ruleService == null) - { - ruleService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getRuleService(); - } - return ruleService; - } - - /** - * Sets the rulesDialog instance to be used by the wizard in edit mode - * - * @param RulesDialog The rulesDialog - */ - public void setRulesDialog(RulesDialog RulesDialog) - { - this.rulesDialog = RulesDialog; - } - - - // ------------------------------------------------------------------------------ - // Helper methods - - /** - * Sets up the given rule using the current state of the wizard - * - * @param context FacesContext - * @param rule The rule to setup - * @param outcome The default outcome - * @return The outcome - */ - @SuppressWarnings("unchecked") - protected String setupRule(FacesContext context, Rule rule, String outcome) - { - if (logger.isDebugEnabled()) - logger.debug("Saving Rules - setupRule"); - - // setup the rule and add it to the space - rule.setTitle(this.title); - rule.setDescription(this.description); - rule.applyToChildren(this.applyToSubSpaces); - rule.setExecuteAsynchronously(this.runInBackground); - rule.setRuleDisabled(this.ruleDisabled); - - CompositeAction compositeAction = this.getActionService().createCompositeAction(); - rule.setAction(compositeAction); - int i = 1; - // add all the conditions to the rule - for (Object condParamsObj : this.allConditionsPropertiesList) - { - if (logger.isDebugEnabled()) - logger.debug("Saving Condition " + i++ + " of " + this.allConditionsPropertiesList.size()); - - Map uiConditionParams = (Map) condParamsObj; - - ActionCondition condition = createCondition(uiConditionParams); - - if (condition instanceof CompositeActionCondition) - { - CompositeActionCondition compositeCondition = (CompositeActionCondition) condition; - - List> subconditionProps = (List>) uiConditionParams - .get(CompositeConditionHandler.PROP_COMPOSITE_CONDITION); - int j = 1; - compositeCondition.setORCondition(((Boolean)uiConditionParams.get(CompositeConditionHandler.PROP_CONDITION_OR)).booleanValue()); - compositeCondition.setInvertCondition((((Boolean)uiConditionParams.get(CompositeConditionHandler.PROP_CONDITION_NOT)).booleanValue())); - - for (Map props : subconditionProps) - { - if (logger.isDebugEnabled()) - logger.debug("Saving Composite Condition " + j++ + " of " + subconditionProps.size()); - - compositeCondition.addActionCondition(createCondition(props)); - } - } - compositeAction.addActionCondition(condition); - } - - // add all the actions to the rule - for (Map actionParams : this.allActionsProperties) - { - // use the base class version of buildActionParams(), but for this - // we need - // to setup the currentActionProperties and action variables - String actionName = (String) actionParams.get(PROP_ACTION_NAME); - this.action = actionName; - - // get the action handler to prepare for the save - Map repoActionParams = new HashMap(); - IHandler handler = this.actionHandlers.get(this.action); - if (handler != null) - { - handler.prepareForSave(actionParams, repoActionParams); - } - - // add the action to the rule - Action action = this.getActionService().createAction(actionName); - action.setParameterValues(repoActionParams); - compositeAction.addAction(action); - } - - return outcome; - } - - private ActionCondition createCondition(Map uiConditionParams) - { - // get the condition handler to prepare for the save - - String conditionName = (String) uiConditionParams.get(PROP_CONDITION_NAME); - - Map repoCondParams = new HashMap(); - if (logger.isDebugEnabled()) - { - logger.debug("\tSaving " + conditionName); - } - IHandler handler = this.conditionHandlers.get(conditionName); - if (handler != null) - { - handler.prepareForSave(uiConditionParams, repoCondParams); - } - - // add the condition to the rule - ActionCondition condition = this.getActionService().createActionCondition(conditionName); - condition.setParameterValues(repoCondParams); - - // specify whether the condition result should be inverted - Boolean not = (Boolean) uiConditionParams.get(BaseConditionHandler.PROP_CONDITION_NOT); - if (not == null) - { - logger.warn("Property missing NOT parameter value (currently null)"); - not = Boolean.TRUE; - } - condition.setInvertCondition(((Boolean) not).booleanValue()); - return condition; - } - - /** - * Initialises the condition handlers from the current configuration. - */ - protected void initialiseConditionHandlers() - { - if ((this.conditionHandlers == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - ConfigService svc = Application.getConfigService(FacesContext.getCurrentInstance()); - Config wizardCfg = svc.getConfig("Action Wizards"); - if (wizardCfg != null) - { - ConfigElement conditionHandlerCfg = wizardCfg.getConfigElement("condition-handlers"); - if (conditionHandlerCfg != null) - { - this.conditionHandlers = new HashMap(20); - - // instantiate each handler and store in the map - for (ConfigElement child : conditionHandlerCfg.getChildren()) - { - String conditionName = child.getAttribute("name"); - String handlerClass = child.getAttribute("class"); - - if (conditionName != null && conditionName.length() > 0 && handlerClass != null - && handlerClass.length() > 0) - { - try - { - @SuppressWarnings("unchecked") - Class klass = Class.forName(handlerClass); - IHandler handler = (IHandler) klass.newInstance(); - this.conditionHandlers.put(conditionName, handler); - } - catch (Exception e) - { - throw new AlfrescoRuntimeException("Failed to setup condition handler for '" + conditionName - + "'", e); - } - } - } - } - else - { - logger.warn("Could not find 'condition-handlers' configuration element"); - } - } - else - { - logger.warn("Could not find 'Action Wizards' configuration section"); - } - } - } - - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException - { - in.defaultReadObject(); - - this.allConditionsDataModel = new ListDataModel(); - this.allConditionsDataModel.setWrappedData(this.allConditionsPropertiesList); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/rules/DeleteRuleDialog.java b/war/src/main/java/org/alfresco/web/bean/rules/DeleteRuleDialog.java deleted file mode 100644 index 1b50a45e9a..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/rules/DeleteRuleDialog.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.rules; - -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.rule.Rule; -import org.alfresco.service.cmr.rule.RuleService; -import org.springframework.extensions.surf.util.ParameterCheck; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class DeleteRuleDialog extends BaseDialogBean -{ - private static final long serialVersionUID = 2009345695752548885L; - - private static final String MSG_ERROR_DELETE_RULE = "error_delete_rule"; - private static final String MSG_DELETE_RULE = "delete_rule"; - private static final String MSG_YES = "yes"; - private static final String MSG_NO = "no"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - transient private Rule currentRule; - transient private RuleService ruleService; - private static Log logger = LogFactory.getLog(DeleteRuleDialog.class); - - @Override - public void init(Map parameters) - { - super.init(parameters); - - String nodeRef = parameters.get("nodeRef"); - - // make sure nodeRef was supplied - ParameterCheck.mandatoryString("nodeRef", nodeRef); - - if (logger.isDebugEnabled()) - logger.debug("Rule clicked, it's nodeRef is: " + nodeRef); - - this.currentRule = getRuleService().getRule(new NodeRef(nodeRef)); - - } - - /** - * @param ruleService Sets the rule service to use - */ - public void setRuleService(RuleService ruleService) - { - this.ruleService = ruleService; - } - - /** - * @return ruleService - */ - protected RuleService getRuleService() - { - //check for null for cluster environment - if (ruleService == null) - { - ruleService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getRuleService(); - } - return ruleService; - } - - /** - * Returns the current rule - * - * @return The current rule - */ - public Rule getCurrentRule() - { - return this.currentRule; - } - - /** - * @return The space to work against - */ - public Node getSpace() - { - return this.browseBean.getActionSpace(); - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - if (this.currentRule != null) - { - try - { - String ruleTitle = this.currentRule.getTitle(); - - getRuleService().removeRule(getSpace().getNodeRef(), this.currentRule); - - // clear the current rule - this.currentRule = null; - - if (logger.isDebugEnabled()) - logger.debug("Deleted rule '" + ruleTitle + "'"); - } - catch (Throwable err) - { - Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), MSG_ERROR_DELETE_RULE) + err.getMessage(), err); - ReportedException.throwIfNecessary(err); - } - } - else - { - logger.warn("WARNING: deleteOK called without a current Rule!"); - } - - return outcome; - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_DELETE_RULE) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) - + currentRule.getTitle() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_NO); - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_YES); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/rules/EditRuleWizard.java b/war/src/main/java/org/alfresco/web/bean/rules/EditRuleWizard.java deleted file mode 100644 index fa5a8d3d26..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/rules/EditRuleWizard.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.rules; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.service.cmr.action.Action; -import org.alfresco.service.cmr.action.ActionCondition; -import org.alfresco.service.cmr.action.ActionConditionDefinition; -import org.alfresco.service.cmr.action.ActionDefinition; -import org.alfresco.service.cmr.action.CompositeAction; -import org.alfresco.service.cmr.action.CompositeActionCondition; -import org.alfresco.service.cmr.rule.Rule; -import org.alfresco.web.bean.actions.IHandler; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.rules.handlers.BaseConditionHandler; -import org.alfresco.web.bean.rules.handlers.CompositeConditionHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean implementation for the "Edit Rule" wizard - * - * @author gavinc - */ -public class EditRuleWizard extends CreateCompositeRuleWizard -{ - private static final long serialVersionUID = -7222762769396254445L; - - private static final Log logger = LogFactory.getLog(EditRuleWizard.class); - - // ------------------------------------------------------------------------------ - // Wizard implementation - - /* Loads up conditions and actions from the repository - */ - @Override - public void init(Map parameters) - { - super.init(parameters); - - // get hold of the current rule details - Rule rule = this.rulesDialog.getCurrentRule(); - - if (rule == null) - { - throw new AlfrescoRuntimeException("Failed to locate the current rule"); - } - - // populate the bean with current values - this.type = rule.getRuleTypes().get(0); - this.title = rule.getTitle(); - this.description = rule.getDescription(); - this.applyToSubSpaces = rule.isAppliedToChildren(); - this.runInBackground = rule.getExecuteAsynchronously(); - this.ruleDisabled = rule.getRuleDisabled(); - - FacesContext context = FacesContext.getCurrentInstance(); - - // Get the composite action - CompositeAction compositeAction = getCompositeAction(rule); - - populateConditions(context, compositeAction); - - populateActions(context, compositeAction); - - // reset the current condition - this.selectedCondition = null; - - // reset the current action - this.action = null; - } - - protected void populateActions(FacesContext context, CompositeAction compositeAction) - { - // populate the actions list with maps of properties representing each action - List actions = compositeAction.getActions(); - for (Action action : actions) - { - this.currentActionProperties = new HashMap(3); - this.currentEmailRecipientsDataModel = null; - this.action = action.getActionDefinitionName(); - this.currentActionProperties.put(PROP_ACTION_NAME, this.action); - - IHandler handler = this.actionHandlers.get(this.action); - if (handler != null) - { - // use the handler to populate the properties and summary - handler.prepareForEdit(this.currentActionProperties, action.getParameterValues()); - this.currentActionProperties.put(PROP_ACTION_SUMMARY, handler.generateSummary(context, this, - this.currentActionProperties)); - } - else - { - // there's no handler, so we presume it is a no-parameter - // action, use the action title as the summary - ActionDefinition actionDef = this.getActionService().getActionDefinition(this.action); - this.currentActionProperties.put(PROP_ACTION_SUMMARY, actionDef.getTitle()); - // add the no params marker so we can disable the edit action - this.currentActionProperties.put(NO_PARAMS_MARKER, "no-params"); - } - - // add the populated currentActionProperties to the list - this.allActionsProperties.add(this.currentActionProperties); - } - } - - protected void populateConditions(FacesContext context, CompositeAction compositeAction) - { - // populate the conditions list with maps of properties representing each condition - List conditions = compositeAction.getActionConditions(); - for (ActionCondition toplevel_condition : conditions) - { - this.selectedCondition = toplevel_condition.getActionConditionDefinitionName(); - this.currentConditionProperties = new HashMap(); - - if (logger.isDebugEnabled()) - logger.debug("Preparing for Edit Condition " + this.selectedCondition); - - if (toplevel_condition instanceof CompositeActionCondition) - { - if (logger.isDebugEnabled()) - logger.debug("\tDetected CompositeCondition"); - - CompositeActionCondition compositeCondition = (CompositeActionCondition) toplevel_condition; - this.currentCompositeConditionPropertiesList = new ArrayList>(); - - //TODO: add OR property - - for (ActionCondition subcondition : compositeCondition.getActionConditions()) - { - if (logger.isDebugEnabled()) - logger.debug("\tSetting ... SubConditions " + subcondition.getActionConditionDefinitionName()); - - this.selectedCondition = subcondition.getActionConditionDefinitionName(); - Map subConditionProperties = new HashMap(); - populateProperties(context, subcondition, subConditionProperties); - this.currentCompositeConditionPropertiesList.add(subConditionProperties); - } - - this.selectedCondition = CompositeConditionHandler.NAME; - - this.currentConditionProperties.put(CompositeConditionHandler.PROP_COMPOSITE_CONDITION, - (Serializable) this.currentCompositeConditionPropertiesList); - - populateProperties(context, compositeCondition, currentConditionProperties); - - } else - populateProperties(context, toplevel_condition, this.currentConditionProperties); - - // add the populated currentConditionProperties to the list - this.allConditionsPropertiesList.add(this.currentConditionProperties); - - printConditionState(); - - } - } - - - protected void populateProperties(FacesContext context, ActionCondition condition, - Map uiConditionProperties) - { - uiConditionProperties.put(PROP_CONDITION_NAME, this.selectedCondition); - uiConditionProperties.put(BaseConditionHandler.PROP_CONDITION_NOT, Boolean.valueOf(condition.getInvertCondition())); - - IHandler handler = this.conditionHandlers.get(this.selectedCondition); - if (handler != null) - { - // use the handler to populate the properties and summary - handler.prepareForEdit(uiConditionProperties, condition.getParameterValues()); - uiConditionProperties.put(PROP_CONDITION_SUMMARY, handler - .generateSummary(context, this, uiConditionProperties)); - } else - { - // there's no handler, so we presume it is a no-parameter - // condition, use the condition title as the summary - ActionConditionDefinition conditionDef = this.getActionService().getActionConditionDefinition(this.selectedCondition); - uiConditionProperties.put(PROP_CONDITION_SUMMARY, conditionDef.getTitle()); - // add the no params marker so we can disable the edit action - uiConditionProperties.put(NO_PARAMS_MARKER, "no-params"); - } - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - // get hold of the space the rule will apply to and make sure - // it is actionable - Node currentSpace = browseBean.getActionSpace(); - - // get the existing rule - Rule rule = this.rulesDialog.getCurrentRule(); - - // Get the composite action - CompositeAction compositeAction = getCompositeAction(rule); - - // remove all the conditions and actions from the current rule - compositeAction.removeAllActionConditions(); - compositeAction.removeAllActions(); - - // re-setup the rule - outcome = setupRule(context, rule, outcome); - - // Save the rule - this.getRuleService().saveRule(currentSpace.getNodeRef(), rule); - - if (logger.isDebugEnabled()) - logger.debug("Updated rule '" + this.title + "'"); - - return outcome; - } - - // ------------------------------------------------------------------------------ - // Bean Getters and Setters - - /** - * Determines whether the rule type drop down list should be enabled. - * - * @return true as the rule type drop down should be disabled - */ - public boolean getRuleTypeDisabled() - { - return true; - } - - // ------------------------------------------------------------------------------ - // Helper methods - -} diff --git a/war/src/main/java/org/alfresco/web/bean/rules/RulesDialog.java b/war/src/main/java/org/alfresco/web/bean/rules/RulesDialog.java deleted file mode 100644 index 965d03ec95..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/rules/RulesDialog.java +++ /dev/null @@ -1,551 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.rules; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; - -import javax.faces.application.FacesMessage; -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.action.executer.ExecuteAllRulesActionExecuter; -import org.alfresco.repo.rule.RuleModel; -import org.alfresco.service.cmr.action.Action; -import org.alfresco.service.cmr.action.ActionService; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.rule.Rule; -import org.alfresco.service.cmr.rule.RuleService; -import org.alfresco.service.namespace.QName; -import org.alfresco.service.namespace.RegexQNamePattern; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.IContextListener; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.dialog.FilterViewSupport; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.alfresco.web.ui.common.component.UIListItem; -import org.alfresco.web.ui.common.component.UIModeList; -import org.alfresco.web.ui.common.component.data.UIRichList; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Backing bean for the manage content rules dialog - * - * @author gavinc - */ -public class RulesDialog extends BaseDialogBean implements IContextListener, FilterViewSupport -{ - private static final long serialVersionUID = -1255494344597331464L; - - private static final String MSG_REAPPLY_RULES_SUCCESS = "reapply_rules_success"; - private static final String MSG_IGNORE_INHERTIED_RULES = "ignore_inherited_rules"; - private static final String MSG_INCLUDE_INHERITED_RULES = "include_inherited_rules"; - private static final String LOCAL = "local"; - private static final String INHERITED = "inherited"; - private final static String MSG_CLOSE = "close"; - - - - private static Log logger = LogFactory.getLog(RulesDialog.class); - - private String filterModeMode = INHERITED; - - transient private RuleService ruleService; - private List rules; - transient private Rule currentRule; - private UIRichList richList; - transient private ActionService actionService; - - /** - * Default constructor - */ - public RulesDialog() - { - super(); - UIContextService.getInstance(FacesContext.getCurrentInstance()).registerBean(this); - } - - - /** - * @return The space to work against - */ - public Node getSpace() - { - return this.browseBean.getActionSpace(); - } - - /** - * Returns the current rule - * - * @return The current rule - */ - public Rule getCurrentRule() - { - return this.currentRule; - } - - /** - * Returns the list of rules to display - * - * @return List of WrappedRule objects - */ - public List getRules() - { - boolean includeInherited = true; - - if (this.filterModeMode.equals(LOCAL)) - { - includeInherited = false; - } - - // get the rules from the repository - List repoRules = this.getRuleService().getRules(getSpace().getNodeRef(), includeInherited); - this.rules = new ArrayList(repoRules.size()); - - // wrap them all passing the current space - for (Rule rule : repoRules) - { - Date createdDate = (Date)this.getNodeService().getProperty(rule.getNodeRef(), ContentModel.PROP_CREATED); - Date modifiedDate = (Date)this.getNodeService().getProperty(rule.getNodeRef(), ContentModel.PROP_MODIFIED); - boolean isLocal = getSpace().getNodeRef().equals(this.getRuleService().getOwningNodeRef(rule)); - - WrappedRule wrapped = new WrappedRule(rule, isLocal, createdDate, modifiedDate); - this.rules.add(wrapped); - } - - return this.rules; - } - - /** - * Handles a rule being clicked ready for an action i.e. edit or delete - * - * @param event The event representing the click - */ - public void setupRuleAction(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - if (logger.isDebugEnabled()) - logger.debug("Rule clicked, it's id is: " + id); - - this.currentRule = this.getRuleService().getRule(new NodeRef(id)); - - // refresh list - contextUpdated(); - } - } - - /** - * Reapply the currently defines rules to the - * @param event ActionEvent - */ - public void reapplyRules(ActionEvent event) - { - boolean toChildren = false; - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String toChildrenStr = params.get("toChildren"); - if (toChildrenStr != null) - { - toChildren = new Boolean(toChildrenStr).booleanValue(); - } - - FacesContext fc = FacesContext.getCurrentInstance(); - UserTransaction tx = null; - - try - { - tx = Repository.getUserTransaction(fc); - tx.begin(); - - // Set the include inherited parameter to match the current filter value - boolean executeInherited = true; - if (this.filterModeMode.equals(LOCAL)) - { - executeInherited = false; - } - - // Reapply the rules - reapplyRules(this.getSpace().getNodeRef(), executeInherited, toChildren); - - // TODO how do I get the message here ... - String msg = Application.getMessage(fc, MSG_REAPPLY_RULES_SUCCESS); - FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg); - String formId = Utils.getParentForm(fc, event.getComponent()).getClientId(fc); - fc.addMessage(formId + ":rulesList", facesMsg); - - // commit the transaction - tx.commit(); - } - catch (Throwable e) - { - // rollback the transaction - try { if (tx != null) {tx.rollback();} } catch (Exception ex) {} - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - fc, Repository.ERROR_GENERIC), e.getMessage()), e); - } - } - - private void reapplyRules(NodeRef space, boolean executeInherited, boolean toChildren) - { - // Create the the apply rules action - Action action = this.getActionService().createAction(ExecuteAllRulesActionExecuter.NAME); - action.setParameterValue(ExecuteAllRulesActionExecuter.PARAM_EXECUTE_INHERITED_RULES, executeInherited); - - // Execute the action - this.getActionService().executeAction(action, space); - - if (toChildren == true) - { - List assocs = getNodeService().getChildAssocs(space, ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL); - for (ChildAssociationRef assoc : assocs) - { - NodeRef nodeRef = assoc.getChildRef(); - QName className = getNodeService().getType(nodeRef); - if (getDictionaryService().isSubClass(className, ContentModel.TYPE_FOLDER) == true) - { - reapplyRules(nodeRef, executeInherited, toChildren); - } - } - } - } - - /** - * Gets the label id from the ignore inhertied action - * - * @return the message id - */ - public String getIgnoreInheritedRulesLabelId() - { - FacesContext fc = FacesContext.getCurrentInstance(); - String result = Application.getMessage(fc, MSG_IGNORE_INHERTIED_RULES); - - if (this.getNodeService().hasAspect(this.getSpace().getNodeRef(), RuleModel.ASPECT_IGNORE_INHERITED_RULES) == true) - { - result = Application.getMessage(fc, MSG_INCLUDE_INHERITED_RULES); - } - return result; - } - - public boolean getIgnoreInheritedRules() - { - return this.getNodeService().hasAspect(this.getSpace().getNodeRef(), RuleModel.ASPECT_IGNORE_INHERITED_RULES); - } - - /** - * Action listener to ignore (or include) inherited rules. - * - * @param event the action event object - */ - public void ignoreInheritedRules(ActionEvent event) - { - NodeRef nodeRef = this.getSpace().getNodeRef(); - if (this.getNodeService().hasAspect(nodeRef, RuleModel.ASPECT_IGNORE_INHERITED_RULES) == true) - { - this.getNodeService().removeAspect(nodeRef, RuleModel.ASPECT_IGNORE_INHERITED_RULES); - } - else - { - this.getNodeService().addAspect(nodeRef, RuleModel.ASPECT_IGNORE_INHERITED_RULES, null); - } - - // force the list to be re-queried when the page is refreshed - if (this.richList != null) - { - this.richList.setValue(null); - } - } - - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - @Override - public void restored() - { - super.restored(); - contextUpdated(); - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } - - /** - * Sets the UIRichList component being used by this backing bean - * - * @param richList UIRichList component - */ - public void setRichList(UIRichList richList) - { - this.richList = richList; - } - - /** - * Returns the UIRichList component being used by this backing bean - * - * @return UIRichList component - */ - public UIRichList getRichList() - { - return this.richList; - } - - - /** - * @param ruleService Sets the rule service to use - */ - public void setRuleService(RuleService ruleService) - { - this.ruleService = ruleService; - } - - protected RuleService getRuleService() - { - if (ruleService == null) - { - ruleService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getRuleService(); - } - return ruleService; - } - - /** - * Set the action service to use - * - * @param actionService the action service - */ - public void setActionService(ActionService actionService) - { - this.actionService = actionService; - } - - private ActionService getActionService() - { - if (actionService == null) - { - actionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getActionService(); - } - return actionService; - } - - // ------------------------------------------------------------------------------ - // IContextListener implementation - - /** - * @see org.alfresco.web.app.context.IContextListener#contextUpdated() - */ - public void contextUpdated() - { - if (this.richList != null) - { - this.richList.setValue(null); - } - } - - /** - * @see org.alfresco.web.app.context.IContextListener#areaChanged() - */ - public void areaChanged() - { - // nothing to do - } - - /** - * @see org.alfresco.web.app.context.IContextListener#spaceChanged() - */ - public void spaceChanged() - { - // nothing to do - } - - /** - * Inner class to wrap the Rule objects so we can expose a flag to indicate whether - * the rule is a local or inherited rule - */ - public static class WrappedRule implements Serializable - { - private static final long serialVersionUID = -8887443730660109283L; - - transient private Rule rule; - private boolean isLocal; - private Date createdDate; - private Date modifiedDate; - - /** - * Constructs a RuleWrapper object - * - * @param rule The rule we are wrapping - * @param isLocal Whether the rule is defined locally - * @param createdDate Date the rule was created - * @param modifiedDate The date the rule was last modified - */ - public WrappedRule(Rule rule, boolean isLocal, Date createdDate, Date modifiedDate) - { - this.rule = rule; - this.isLocal = isLocal; - this.createdDate = createdDate; - this.modifiedDate = modifiedDate; - } - - /** - * Returns the rule being wrapped - * - * @return The wrapped Rule - */ - public Rule getRule() - { - return this.rule; - } - - /** - * Determines whether the current rule is a local rule or - * has been inherited from a parent - * - * @return true if the rule is defined on the current node - */ - public boolean getLocal() - { - return this.isLocal; - } - - /** Methods to support sorting of the rules list in a table */ - - /** - * Returns the rule id - * - * @return The id - */ - public String getId() - { - return this.rule.getNodeRef().toString(); - } - - /** - * Returns the rule title - * - * @return The title - */ - public String getTitle() - { - return this.rule.getTitle(); - } - - /** - * Returns the rule description - * - * @return The description - */ - public String getDescription() - { - return this.rule.getDescription(); - } - - /** - * Returns the created date - * - * @return The created date - */ - public Date getCreatedDate() - { - return this.createdDate; - } - - /** - * Returns the modfified date - * - * @return The modified date - */ - public Date getModifiedDate() - { - return this.modifiedDate; - } - } - - public void filterModeChanged(ActionEvent event) - { - UIModeList viewList = (UIModeList)event.getComponent(); - this.filterModeMode = viewList.getValue().toString(); - - // force the list to be re-queried when the page is refreshed - if (this.richList != null) - { - this.richList.setValue(null); - } - } - - public List getFilterItems() - { - FacesContext context = FacesContext.getCurrentInstance(); - List items = new ArrayList(2); - - UIListItem item1 = new UIListItem(); - item1.setValue(INHERITED); - item1.setLabel(Application.getMessage(context, INHERITED)); - items.add(item1); - - UIListItem item2 = new UIListItem(); - item2.setValue(LOCAL); - item2.setLabel(Application.getMessage(context, LOCAL)); - items.add(item2); - - return items; - } - - public String getFilterMode() - { - return filterModeMode; - } - - public void setFilterMode(String filterMode) - { - this.filterModeMode = filterMode; - - // clear datalist cache ready to change results based on filter setting - contextUpdated(); - - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/rules/handlers/BaseConditionHandler.java b/war/src/main/java/org/alfresco/web/bean/rules/handlers/BaseConditionHandler.java deleted file mode 100644 index 772f8b6b6d..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/rules/handlers/BaseConditionHandler.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.rules.handlers; - -import java.io.Serializable; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.web.bean.actions.IHandler; -import org.alfresco.web.bean.repository.Repository; - -/** - * Base class for all condition handler implementations. - * - * @author gavinc - */ -public abstract class BaseConditionHandler implements IHandler -{ - protected static final String CONDITION_PAGES_LOCATION = "/jsp/rules/"; - public static final String PROP_CONDITION_NOT = "notcondition"; - - public void setupUIDefaults(Map conditionProps) - { - // do nothing by default, only those condition handlers that need - // to setup defaults need override this method - } - - /** - * Given the condition name, generates the default path for the JSP - * - * @param conditionName The name of the condition - * @return The path to the JSP used for the condition - */ - protected String getJSPPath(String conditionName) - { - return CONDITION_PAGES_LOCATION + conditionName + ".jsp"; - } - - /** - * Returns the NamespaceService for further retrieve a prefix strings. - * - * @see org.alfresco.web.bean.rules.handlers.property.TextPropertyValueConditionHandler#prepareForEdit(Map, Map) - * - * @return The NamespaseService for further usage - */ - protected NamespaceService getNamespaceService() - { - return Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNamespaceService(); - } - - /* - * @see org.alfresco.web.bean.actions.IHandler#isAllowMultiple() - */ - public boolean isAllowMultiple() - { - return true; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/rules/handlers/CompareMimeTypeHandler.java b/war/src/main/java/org/alfresco/web/bean/rules/handlers/CompareMimeTypeHandler.java deleted file mode 100644 index 64738c1d4e..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/rules/handlers/CompareMimeTypeHandler.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.rules.handlers; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.model.SelectItem; - -import org.alfresco.repo.action.evaluator.CompareMimeTypeEvaluator; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.rules.CreateRuleWizard; -import org.alfresco.web.bean.wizard.IWizardBean; - -/** - * Condition handler for the "compare-mime-type" condition - * - * @author gavinc - */ -public class CompareMimeTypeHandler extends BaseConditionHandler -{ - private static final long serialVersionUID = 6421611697032505073L; - - protected static final String PROP_MIMETYPE = "mimetype"; - - public String getJSPPath() - { - return getJSPPath(CompareMimeTypeEvaluator.NAME); - } - - public void prepareForSave(Map conditionProps, - Map repoProps) - { - String mimeType = (String)conditionProps.get(PROP_MIMETYPE); - repoProps.put(CompareMimeTypeEvaluator.PARAM_VALUE, mimeType); - } - - public void prepareForEdit(Map conditionProps, - Map repoProps) - { - String mimeType = (String)repoProps.get(CompareMimeTypeEvaluator.PARAM_VALUE); - conditionProps.put(PROP_MIMETYPE, mimeType); - } - - public String generateSummary(FacesContext context, IWizardBean wizard, - Map conditionProps) - { - Boolean not = (Boolean)conditionProps.get(PROP_CONDITION_NOT); - String msgId = not.booleanValue() ? "condition_compare_mime_type_not" : "condition_compare_mime_type"; - - String label = null; - String mimetype = (String)conditionProps.get(PROP_MIMETYPE); - for (SelectItem item : ((CreateRuleWizard)wizard).getMimeTypes()) - { - if (item.getValue().equals(mimetype)) - { - label = item.getLabel(); - break; - } - } - - return MessageFormat.format(Application.getMessage(context, msgId), - new Object[] {label}); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/rules/handlers/CompositeConditionHandler.java b/war/src/main/java/org/alfresco/web/bean/rules/handlers/CompositeConditionHandler.java deleted file mode 100644 index 79662998bc..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/rules/handlers/CompositeConditionHandler.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.rules.handlers; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.repo.action.ActionModel; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.wizard.IWizardBean; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * @author Jean Barmash - * This class has no equivalent evaluator, since it - * - */ -public class CompositeConditionHandler extends BaseConditionHandler -{ - public static final String NAME = "composite-condition"; - public static final String PROP_COMPOSITE_CONDITION = "composite-condition"; - - private static final Log logger = LogFactory.getLog(CompositeConditionHandler.class); - - public static final String PROP_CONDITION_OR = "orconditions"; - - /* (non-Javadoc) - * @see org.alfresco.web.bean.actions.IHandler#generateSummary(javax.faces.context.FacesContext, org.alfresco.web.bean.wizard.IWizardBean, java.util.Map) - */ - public String generateSummary(FacesContext context, IWizardBean wizard, - Map props) - { - List conditionPropertiesList = (List) props.get(PROP_COMPOSITE_CONDITION); - if (conditionPropertiesList == null ) - { - logger.error("Error - composite condition has no sub-conditions"); - - if (logger.isDebugEnabled()) - { - for (String str : props.keySet()) - { - logger.debug("\t key - "+ str + " value " + props.get(str)); - } - } - - return Application.getMessage(context, "condition_composite_error"); - } - - Boolean not = (Boolean) props.get(PROP_CONDITION_NOT); - Boolean orconditions = (Boolean) props.get(PROP_CONDITION_OR); - - String msgId = not.booleanValue() ? "condition_composite_summary_not" : "condition_composite_summary"; - return MessageFormat.format(Application.getMessage(context, msgId), - new Object[] {conditionPropertiesList.size(), orconditions.booleanValue()?"ORed":"ANDed"}); - } - - /* (non-Javadoc) - * @see org.alfresco.web.bean.actions.IHandler#getJSPPath() - */ - public String getJSPPath() - { - return getJSPPath(CompositeConditionHandler.NAME); - } - - /* (non-Javadoc) - * @see org.alfresco.web.bean.actions.IHandler#prepareForEdit(java.util.Map, java.util.Map) - */ - public void prepareForEdit(Map uiConditionProps, - Map repoProps) - { - if (logger.isDebugEnabled()) - logger.debug("Preparing Composite Condition for Edit"); - - Boolean orconditions = (Boolean) repoProps.get(PROP_CONDITION_OR); - if (orconditions == null) - { - if (logger.isWarnEnabled()) - logger.warn("orconditions is NULL, it should not be. Defaulting to false"); - - orconditions = Boolean.FALSE; - } - - uiConditionProps.put(PROP_CONDITION_OR, orconditions); - } - - public void prepareForSave(Map uiConditionProps, - Map repoProps) - { - if (logger.isDebugEnabled()) - logger.debug("Saving Composite Condition"); - - // put the selected category in the condition params - Boolean orconditions = (Boolean)uiConditionProps.get(PROP_CONDITION_OR); - if (orconditions == null) - { - if (logger.isWarnEnabled()) - logger.warn("orconditions is NULL, it should not be. Defaulting to false"); - - orconditions = Boolean.FALSE; - } - - repoProps.put(PROP_CONDITION_OR, orconditions); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/rules/handlers/HasAspectHandler.java b/war/src/main/java/org/alfresco/web/bean/rules/handlers/HasAspectHandler.java deleted file mode 100644 index f0abd3a424..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/rules/handlers/HasAspectHandler.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.rules.handlers; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.model.SelectItem; - -import org.alfresco.repo.action.evaluator.HasAspectEvaluator; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.rules.CreateRuleWizard; -import org.alfresco.web.bean.wizard.IWizardBean; - -/** - * Condition handler for the "has-aspect" condition. - * - * @author gavinc - */ -public class HasAspectHandler extends BaseConditionHandler -{ - private static final long serialVersionUID = 7365950247553882237L; - - protected static final String PROP_ASPECT = "aspect"; - - public String getJSPPath() - { - return getJSPPath(HasAspectEvaluator.NAME); - } - - public void prepareForSave(Map conditionProps, - Map repoProps) - { - QName aspect = QName.createQName((String)conditionProps.get(PROP_ASPECT)); - repoProps.put(HasAspectEvaluator.PARAM_ASPECT, aspect); - } - - public void prepareForEdit(Map conditionProps, - Map repoProps) - { - QName aspect = (QName)repoProps.get(HasAspectEvaluator.PARAM_ASPECT); - conditionProps.put(PROP_ASPECT, aspect.toString()); - } - - public String generateSummary(FacesContext context, IWizardBean wizard, - Map conditionProps) - { - Boolean not = (Boolean)conditionProps.get(PROP_CONDITION_NOT); - String msgId = not.booleanValue() ? "condition_has_aspect_not" : "condition_has_aspect"; - - String label = null; - String aspectName = (String)conditionProps.get(PROP_ASPECT); - for (SelectItem item : ((CreateRuleWizard)wizard).getTestableAspects()) - { - if (item.getValue().equals(aspectName)) - { - label = item.getLabel(); - break; - } - } - - return MessageFormat.format(Application.getMessage(context, msgId), - new Object[] {label}); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/rules/handlers/HasTagHandler.java b/war/src/main/java/org/alfresco/web/bean/rules/handlers/HasTagHandler.java deleted file mode 100644 index b01006bc71..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/rules/handlers/HasTagHandler.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.rules.handlers; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.repo.action.evaluator.HasTagEvaluator; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.wizard.IWizardBean; - -/** - * Condition handler for the "has-tag" condition. - * - * @author arsenyko - */ -public class HasTagHandler extends BaseConditionHandler -{ - private static final long serialVersionUID = 1L; - - public String getJSPPath() - { - return getJSPPath(HasTagEvaluator.NAME); - } - - public void prepareForSave(Map conditionProps, - Map repoProps) - { - String tag = (String)conditionProps.get(HasTagEvaluator.PARAM_TAG); - repoProps.put(HasTagEvaluator.PARAM_TAG, tag); - } - - public void prepareForEdit(Map conditionProps, - Map repoProps) - { - String tag = (String)repoProps.get(HasTagEvaluator.PARAM_TAG); - conditionProps.put(HasTagEvaluator.PARAM_TAG, tag); - } - - public String generateSummary(FacesContext context, IWizardBean wizard, - Map conditionProps) - { - Boolean not = (Boolean)conditionProps.get(PROP_CONDITION_NOT); - String msgId = not.booleanValue() ? "condition_has_tag_not" : "condition_has_tag"; - - String label = (String) conditionProps.get(HasTagEvaluator.PARAM_TAG); - - return MessageFormat.format(Application.getMessage(context, msgId), - new Object[] {label}); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/rules/handlers/InCategoryHandler.java b/war/src/main/java/org/alfresco/web/bean/rules/handlers/InCategoryHandler.java deleted file mode 100644 index e75a5ec7c3..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/rules/handlers/InCategoryHandler.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.rules.handlers; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.action.evaluator.InCategoryEvaluator; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.wizard.IWizardBean; - -/** - * Condition handler for the "in-category" condition. - * - * @author gavinc - */ -public class InCategoryHandler extends BaseConditionHandler -{ - private static final long serialVersionUID = -7312917724514125469L; - - protected static final String PROP_CATEGORY = "category"; - - public String getJSPPath() - { - return getJSPPath(InCategoryEvaluator.NAME); - } - - public void prepareForSave(Map conditionProps, - Map repoProps) - { - // put the selected category in the condition params - NodeRef nodeRef = (NodeRef)conditionProps.get(PROP_CATEGORY); - repoProps.put(InCategoryEvaluator.PARAM_CATEGORY_VALUE, nodeRef); - - // add the classifiable aspect - repoProps.put(InCategoryEvaluator.PARAM_CATEGORY_ASPECT, - ContentModel.ASPECT_GEN_CLASSIFIABLE); - } - - public void prepareForEdit(Map conditionProps, - Map repoProps) - { - NodeRef catNodeRef = (NodeRef)repoProps.get(InCategoryEvaluator.PARAM_CATEGORY_VALUE); - conditionProps.put(PROP_CATEGORY, catNodeRef); - } - - public String generateSummary(FacesContext context, IWizardBean wizard, - Map conditionProps) - { - Boolean not = (Boolean)conditionProps.get(PROP_CONDITION_NOT); - String msgId = not.booleanValue() ? "condition_in_category_not" : "condition_in_category"; - - String name = Repository.getNameForNode(Repository.getServiceRegistry(context). - getNodeService(), (NodeRef)conditionProps.get(PROP_CATEGORY)); - - return MessageFormat.format(Application.getMessage(context, msgId), - new Object[] {name}); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/rules/handlers/IsSubTypeHandler.java b/war/src/main/java/org/alfresco/web/bean/rules/handlers/IsSubTypeHandler.java deleted file mode 100644 index 528b1dc262..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/rules/handlers/IsSubTypeHandler.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.rules.handlers; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.model.SelectItem; - -import org.alfresco.repo.action.evaluator.IsSubTypeEvaluator; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.rules.CreateRuleWizard; -import org.alfresco.web.bean.wizard.IWizardBean; - -/** - * Condition handler to the "is-subtype" condition. - * - * @author gavinc - */ -public class IsSubTypeHandler extends BaseConditionHandler -{ - private static final long serialVersionUID = 906340104511402964L; - - protected static final String PROP_MODEL_TYPE = "modeltype"; - - public String getJSPPath() - { - return getJSPPath(IsSubTypeEvaluator.NAME); - } - - public void prepareForSave(Map conditionProps, - Map repoProps) - { - QName type = QName.createQName((String)conditionProps.get(PROP_MODEL_TYPE)); - repoProps.put(IsSubTypeEvaluator.PARAM_TYPE, type); - } - - public void prepareForEdit(Map conditionProps, - Map repoProps) - { - QName type = (QName)repoProps.get(IsSubTypeEvaluator.PARAM_TYPE); - conditionProps.put(PROP_MODEL_TYPE, type.toString()); - } - - public String generateSummary(FacesContext context, IWizardBean wizard, - Map conditionProps) - { - Boolean not = (Boolean)conditionProps.get(PROP_CONDITION_NOT); - String msgId = not.booleanValue() ? "condition_is_subtype_not" : "condition_is_subtype"; - - String label = null; - String typeName = (String)conditionProps.get(PROP_MODEL_TYPE); - for (SelectItem item : ((CreateRuleWizard)wizard).getModelTypes()) - { - if (item.getValue().equals(typeName)) - { - label = item.getLabel(); - break; - } - } - - return MessageFormat.format(Application.getMessage(context, msgId), - new Object[] {label}); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/rules/handlers/PropertyValueHandler.java b/war/src/main/java/org/alfresco/web/bean/rules/handlers/PropertyValueHandler.java deleted file mode 100644 index 794bfe99b2..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/rules/handlers/PropertyValueHandler.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.rules.handlers; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.repo.action.evaluator.ComparePropertyValueEvaluator; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.wizard.IWizardBean; - -/** - * Condition handler for the "compare-property-value" condition. - * - * @author gavinc - */ -public class PropertyValueHandler extends BaseConditionHandler -{ - private static final long serialVersionUID = 6718858865738420012L; - - public static final String PROP_CONTAINS_TEXT = "containstext"; - - public String getJSPPath() - { - return getJSPPath(ComparePropertyValueEvaluator.NAME); - } - - public void prepareForSave(Map conditionProps, - Map repoProps) - { - prepareForSaveWithCorrectType(conditionProps, repoProps); - } - - //Responsible for serializing the value of the property, which could have different types - protected void prepareForSaveWithCorrectType(Map conditionProps, Map repoProps) - { - String text = (String)conditionProps.get(PROP_CONTAINS_TEXT); - repoProps.put(ComparePropertyValueEvaluator.PARAM_VALUE, text); - } - - public void prepareForEdit(Map conditionProps, - Map repoProps) - { - prepareForEditWithCorrectType(conditionProps, repoProps); - } - - protected void prepareForEditWithCorrectType(Map conditionProps, - Map repoProps) - { - String propValue = (String)repoProps.get(ComparePropertyValueEvaluator.PARAM_VALUE); - conditionProps.put(PROP_CONTAINS_TEXT, propValue); - } - - - public String generateSummary(FacesContext context, IWizardBean wizard, - Map conditionProps) - { - Boolean not = (Boolean)conditionProps.get(PROP_CONDITION_NOT); - String msgId = not.booleanValue() ? - "condition_compare_property_value_not" : "condition_compare_property_value"; - - String text = (String)conditionProps.get(PROP_CONTAINS_TEXT); - - return MessageFormat.format(Application.getMessage(context, msgId), - new Object[] {text}); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/rules/handlers/property/DatePropertyValueConditionHandler.java b/war/src/main/java/org/alfresco/web/bean/rules/handlers/property/DatePropertyValueConditionHandler.java deleted file mode 100644 index 122e8a8501..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/rules/handlers/property/DatePropertyValueConditionHandler.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.rules.handlers.property; - -import java.io.Serializable; -import java.util.Date; -import java.util.Map; - -import org.alfresco.repo.action.evaluator.ComparePropertyValueEvaluator; -import org.alfresco.repo.action.evaluator.compare.ComparePropertyValueOperation; - -/** - * Condition handler for the "compare-date-property" condition. - * - * @author Jean Barmash - */ -public class DatePropertyValueConditionHandler extends TextPropertyValueConditionHandler -{ - - public static final String NAME = "compare-date-property"; - - @Override - protected String getConditionName() - { - return DatePropertyValueConditionHandler.NAME; - } - - //Responsible for serializing the value of the property, which could have different types - protected void prepareForSaveWithCorrectType(Map conditionProps, Map repoProps) - { - Date date = (Date) conditionProps.get(PROP_CONTAINS_TEXT); - repoProps.put(ComparePropertyValueEvaluator.PARAM_VALUE, date); - } - - protected void prepareForEditWithCorrectType(Map conditionProps, - Map repoProps) - { - Date dateValue = (Date) repoProps.get(ComparePropertyValueEvaluator.PARAM_VALUE); - conditionProps.put(PROP_CONTAINS_TEXT, dateValue); - } - - @Override - protected String getSummaryStringTemplate(Boolean not) - { - String msgId = not.booleanValue() ? "condition_compare_date_property_value_not" - : "condition_compare_date_property_value"; - return msgId; - } - - @Override - protected String displayOperation(String operation) - { - ComparePropertyValueOperation op = ComparePropertyValueOperation.valueOf(operation); - switch (op) - { - case EQUALS: - return "property_date_condition_equals"; - case GREATER_THAN: - return "property_date_condition_greaterthan"; - case GREATER_THAN_EQUAL: - return "property_date_condition_greaterthanequals"; - case LESS_THAN: - return "property_date_condition_lessthan"; - case LESS_THAN_EQUAL: - return "property_date_condition_lessthanequals"; - default: return "property_condition_invalid"; - } - } - - -} diff --git a/war/src/main/java/org/alfresco/web/bean/rules/handlers/property/IntegerPropertyValueConditionHandler.java b/war/src/main/java/org/alfresco/web/bean/rules/handlers/property/IntegerPropertyValueConditionHandler.java deleted file mode 100644 index bfea808bb0..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/rules/handlers/property/IntegerPropertyValueConditionHandler.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.rules.handlers.property; - -import java.io.Serializable; -import java.util.Map; - -import org.alfresco.repo.action.evaluator.ComparePropertyValueEvaluator; -import org.alfresco.repo.action.evaluator.compare.ComparePropertyValueOperation; - -/** - * Condition handler for the "compare-integer-property" condition. - * - * @author Jean Barmash - */ -public class IntegerPropertyValueConditionHandler extends TextPropertyValueConditionHandler -{ - - public static final String NAME = "compare-integer-property"; - - @Override - protected String getConditionName() - { - return IntegerPropertyValueConditionHandler.NAME; - } - - //Responsible for serializing the value of the property, which could have different types - protected void prepareForSaveWithCorrectType(Map conditionProps, Map repoProps) - { - Long number = Long.parseLong((String)conditionProps.get(PROP_CONTAINS_TEXT)); - repoProps.put(ComparePropertyValueEvaluator.PARAM_VALUE, number ); - } - - protected void prepareForEditWithCorrectType(Map conditionProps, - Map repoProps) - { - Long propValue = (Long)repoProps.get(ComparePropertyValueEvaluator.PARAM_VALUE); - conditionProps.put(PROP_CONTAINS_TEXT, propValue.toString()); - } - - @Override - protected String getSummaryStringTemplate(Boolean not) - { - String msgId = not.booleanValue() ? "condition_compare_integer_property_value_not" - : "condition_compare_integer_property_value"; - return msgId; - } - - @Override - protected String displayOperation(String operation) - { - ComparePropertyValueOperation op = ComparePropertyValueOperation.valueOf(operation); - switch (op) - { - case EQUALS: - return "property_condition_equals"; - case GREATER_THAN: - return "property_condition_greaterthan"; - case GREATER_THAN_EQUAL: - return "property_condition_greaterthanequals"; - case LESS_THAN: - return "property_condition_lessthan"; - case LESS_THAN_EQUAL: - return "property_condition_lessthanequals"; - default: return "property_condition_invalid"; - } - } - - -} diff --git a/war/src/main/java/org/alfresco/web/bean/rules/handlers/property/TextPropertyValueConditionHandler.java b/war/src/main/java/org/alfresco/web/bean/rules/handlers/property/TextPropertyValueConditionHandler.java deleted file mode 100644 index 6c0482a32d..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/rules/handlers/property/TextPropertyValueConditionHandler.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.rules.handlers.property; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.repo.action.evaluator.ComparePropertyValueEvaluator; -import org.alfresco.repo.action.evaluator.compare.ComparePropertyValueOperation; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.rules.handlers.PropertyValueHandler; -import org.alfresco.web.bean.wizard.IWizardBean; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Condition handler for the "compare-text-property" condition. - * - * @author Jean Barmash - */ -public class TextPropertyValueConditionHandler extends PropertyValueHandler -{ - private static final Log logger = LogFactory.getLog(TextPropertyValueConditionHandler.class); - public static final String NAME = "compare-text-property"; - - public static final String UI_PARAM_OPERATION = "operation"; - public static final String UI_PARAM_QNAME = "qname"; - private static final String DEFAULT_NAMESPACE = NamespaceService.CONTENT_MODEL_PREFIX; - - public String getJSPPath() - { - return getJSPPath(getConditionName()); - } - - protected String getConditionName() - { - return TextPropertyValueConditionHandler.NAME; - } - - public void prepareForSave(Map conditionParams, Map repoProps) - { - if (logger.isDebugEnabled()) - logger.debug("Preparing to Save Text Condition Parameters"); - - super.prepareForSave(conditionParams, repoProps); - String propertyString = (String) conditionParams.get(UI_PARAM_QNAME); - - QName qname = null; - - // TODO: there might be a better way to resolve namespaces instead of propertyString.indexOf(':')? - - // The part of ADB-131 fix. We use default namespase prefix of content model 'cm'. - // It is necessary to enable an ability to set the property as its localName (e.g. description). - // It keeps also an ability to enter a user content model text properties such as 'my:description' - propertyString = propertyString.indexOf(':') == -1 ? - DEFAULT_NAMESPACE + QName.NAMESPACE_PREFIX + propertyString : - propertyString; - qname = QName.createQName(propertyString, getNamespaceService()); - if (logger.isDebugEnabled()) - logger.warn("Storing Property QName " + qname); - - repoProps.put(ComparePropertyValueEvaluator.PARAM_PROPERTY, qname); - - String operation = (String) conditionParams.get(UI_PARAM_OPERATION); - repoProps.put(ComparePropertyValueEvaluator.PARAM_OPERATION, operation); - } - - public void prepareForEdit(Map conditionProps, Map repoProps) - { - if (logger.isDebugEnabled()) - logger.debug("Retrieving Text Condition Parameters for editing"); - - super.prepareForEdit(conditionProps, repoProps); - // The part of ADB-131 fix. The NamespaceService is used to get a valid prefix string. - // When the user attempt to edit a rule a 'Summary' string contain an invalid property name - // and then the property will be saved with default prefix 'cm'. But the property may be as 'my:description' - conditionProps.put(UI_PARAM_QNAME, ((QName) repoProps.get(ComparePropertyValueEvaluator.PARAM_PROPERTY)).toPrefixString(getNamespaceService())); - conditionProps.put(UI_PARAM_OPERATION, repoProps.get(ComparePropertyValueEvaluator.PARAM_OPERATION).toString()); - } - - public String generateSummary(FacesContext context, IWizardBean wizard, Map conditionProps) - { - Boolean not = (Boolean) conditionProps.get(PROP_CONDITION_NOT); - String msgId = getSummaryStringTemplate(not); - String text = conditionProps.get(PROP_CONTAINS_TEXT).toString(); - String operation = (String) conditionProps.get(UI_PARAM_OPERATION); - String qname = (String) conditionProps.get(UI_PARAM_QNAME); - - return MessageFormat.format(Application.getMessage(context, msgId), new Object[] - { qname, Application.getMessage(context, displayOperation(operation)), text }); - } - - protected String displayOperation(String operation) - { - ComparePropertyValueOperation op = ComparePropertyValueOperation.valueOf(operation); - switch (op) - { - case EQUALS: - return "property_date_condition_equals"; - case CONTAINS: - return "property_condition_contains"; - case BEGINS: - return "property_condition_beginswith"; - case ENDS: - return "property_condition_endswith"; - default: return "property_condition_invalid"; - } - } - - protected String getSummaryStringTemplate(Boolean not) - { - String msgId = not.booleanValue() ? "condition_compare_text_property_value_not" - : "condition_compare_text_property_value"; - return msgId; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/search/AdvancedSearchDialog.java b/war/src/main/java/org/alfresco/web/bean/search/AdvancedSearchDialog.java deleted file mode 100644 index 1052aa24dc..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/search/AdvancedSearchDialog.java +++ /dev/null @@ -1,1126 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.search; - -import java.text.MessageFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.component.UISelectBoolean; -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.faces.model.DataModel; -import javax.faces.model.SelectItem; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.security.permissions.AccessDeniedException; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.dictionary.AspectDefinition; -import org.alfresco.service.cmr.dictionary.DataTypeDefinition; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.cmr.dictionary.TypeDefinition; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.ContentReader; -import org.alfresco.service.cmr.repository.ContentService; -import org.alfresco.service.cmr.repository.MimetypeService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.security.AccessStatus; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.service.namespace.RegexQNamePattern; -import org.alfresco.util.CachingDateFormat; -import org.alfresco.util.ISO9075; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.MapNode; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.repository.User; -import org.alfresco.web.bean.search.SearchContext.RangeProperties; -import org.alfresco.web.config.AdvancedSearchConfigElement; -import org.alfresco.web.config.AdvancedSearchConfigElement.CustomProperty; -import org.alfresco.web.data.IDataContainer; -import org.alfresco.web.data.QuickSort; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIModeList; -import org.alfresco.web.ui.common.component.UIPanel.ExpandedEvent; -import org.alfresco.web.ui.repo.component.UIAjaxCategoryPicker; -import org.alfresco.web.ui.repo.component.UISearchCustomProperties; - -/** - * Provides the form state and action event handling for the Advanced Search UI. - *

- * Integrates with the web-client ConfigService to retrieve configuration of custom - * meta-data searching fields. Custom fields can be configured to appear in the UI - * and they are they automatically added to the search query by this bean. - * - * @author Kevin Roast - */ -public class AdvancedSearchDialog extends BaseDialogBean -{ - private static final long serialVersionUID = 3658148969240122732L; - - /** PermissionService */ - transient private PermissionService permissionService; - - /** - * Default constructor - */ - public void init(java.util.Map parameters) - { - super.init(parameters); - properties.getPanels().put(PANEL_CATEGORIES, false); - properties.getPanels().put(PANEL_ATTRS, false); - properties.getPanels().put(PANEL_CUSTOM, false); - } - - - // ------------------------------------------------------------------------------ - // Bean property getters and setters - - public void setPermissionService(PermissionService permissionService) - { - this.permissionService = permissionService; - } - - protected PermissionService getPermissionService() - { - if (permissionService == null) - { - permissionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPermissionService(); - } - return permissionService; - } - - public void setProperties(SearchProperties properties) - { - this.properties = properties; - } - - /** - * @return Returns the allow Edit mode. - */ - public boolean isAllowEdit() - { - boolean allow = (properties.getSavedSearch() != null && NO_SELECTION.equals(properties.getSavedSearch()) == false); - if (allow) - { - NodeRef savedSearchRef = new NodeRef(Repository.getStoreRef(), properties.getSavedSearch()); - allow = (getPermissionService().hasPermission(savedSearchRef, - PermissionService.WRITE) == AccessStatus.ALLOWED); - } - return allow; - } - - /** - * @param allowEdit The allow Edit mode to set. - */ - public void setAllowEdit(boolean allowEdit) - { - // dummy method for Bean interface compliance - } - - /** - * Returns the properties for current categories JSF DataModel - * - * @return JSF DataModel representing the current categories to search against - */ - public DataModel getCategoriesDataModel() - { - // only set the wrapped data once otherwise the rowindex is reset - if (properties.getCategoriesDataModel().getWrappedData() == null) - { - properties.getCategoriesDataModel().setWrappedData(properties.getCategories()); - } - - return properties.getCategoriesDataModel(); - } - - /** - * @return Returns a list of content object types to allow the user to select from - */ - public List getContentTypes() - { - if ((properties.getContentTypes() == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - FacesContext context = FacesContext.getCurrentInstance(); - - DictionaryService dictionaryService = Repository.getServiceRegistry(context).getDictionaryService(); - - // add the well known cm:content object type by default - properties.setContentTypes(new ArrayList(5)); - properties.getContentTypes().add(new SelectItem(ContentModel.TYPE_CONTENT.toString(), - dictionaryService.getType(ContentModel.TYPE_CONTENT).getTitle(dictionaryService))); - - // add any configured content sub-types to the list - List types = getSearchConfig().getContentTypes(); - if (types != null) - { - for (String type : types) - { - QName idQName = Repository.resolveToQName(type); - if (idQName != null) - { - TypeDefinition typeDef = dictionaryService.getType(idQName); - - if (typeDef != null && dictionaryService.isSubClass(typeDef.getName(), ContentModel.TYPE_CONTENT)) - { - // try and get label from the dictionary - String label = typeDef.getTitle(dictionaryService); - - // else just use the localname - if (label == null) - { - label = idQName.getLocalName(); - } - - properties.getContentTypes().add(new SelectItem(idQName.toString(), label)); - } - } - } - } - } - - return properties.getContentTypes(); - } - - /** - * @return Returns a list of folder object types to allow the user to select from - */ - public List getFolderTypes() - { - if ((properties.getFolderTypes() == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - FacesContext context = FacesContext.getCurrentInstance(); - - DictionaryService dictionaryService = Repository.getServiceRegistry(context).getDictionaryService(); - - // add the well known cm:folder object type by default - properties.setFolderTypes(new ArrayList(5)); - properties.getFolderTypes().add(new SelectItem(ContentModel.TYPE_FOLDER.toString(), - dictionaryService.getType(ContentModel.TYPE_FOLDER).getTitle(dictionaryService))); - - // add any configured folder sub-types to the list - List types = getSearchConfig().getFolderTypes(); - if (types != null) - { - for (String type : types) - { - QName idQName = Repository.resolveToQName(type); - if (idQName != null) - { - TypeDefinition typeDef = dictionaryService.getType(idQName); - - if (typeDef != null && dictionaryService.isSubClass(typeDef.getName(), ContentModel.TYPE_FOLDER)) - { - // try and get label from the dictionary - String label = typeDef.getTitle(dictionaryService); - - // else just use the localname - if (label == null) - { - label = idQName.getLocalName(); - } - - properties.getFolderTypes().add(new SelectItem(idQName.toString(), label)); - } - } - } - } - } - - return properties.getFolderTypes(); - } - - /** - * @return Returns a list of content formats to allow the user to select from - */ - public List getContentFormats() - { - if ((properties.getContentFormats() == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - properties.setContentFormats(new ArrayList(80)); - ServiceRegistry registry = Repository.getServiceRegistry(FacesContext.getCurrentInstance()); - MimetypeService mimetypeService = registry.getMimetypeService(); - - // get the mime type display names - Map mimeTypes = mimetypeService.getDisplaysByMimetype(); - for (String mimeType : mimeTypes.keySet()) - { - properties.getContentFormats().add(new SelectItem(mimeType, mimeTypes.get(mimeType))); - } - - // make sure the list is sorted by the values - QuickSort sorter = new QuickSort(properties.getContentFormats(), "label", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - - // add the "All Formats" constant marker at the top of the list (default selection) - properties.getContentFormats().add(0, new SelectItem("", Application.getMessage(FacesContext.getCurrentInstance(), MSG_ALL_FORMATS))); - } - - return properties.getContentFormats(); - } - - - // ------------------------------------------------------------------------------ - // Action event handlers - - /** - * Handler to clear the advanced search screen form details - */ - public void reset(ActionEvent event) - { - resetFields(); - properties.setSavedSearch(null); - } - - private void resetFields() - { - properties.setText(""); - properties.setMode(MODE_ALL); - properties.setLookin(LOOKIN_ALL); - properties.setContentType(null); - properties.setContentFormat(null); - properties.setFolderType(null); - properties.setLocation(null); - properties.setLocationChildren(true); - properties.setCategories(new ArrayList(2)); - properties.setCategoriesDataModel(null); - properties.setTitle(null); - properties.setDescription(null); - properties.setAuthor(null); - properties.setCreatedDateFrom(null); - properties.setCreatedDateTo(null); - properties.setModifiedDateFrom(null); - properties.setModifiedDateTo(null); - properties.setCreatedDateChecked(false); - properties.setModifiedDateChecked(false); - properties.getCustomProperties().clear(); - } - - /** - * Handler to perform a search based on the current criteria - */ - public String search() - { - // construct the Search Context and set on the navigation bean - // then simply navigating to the browse screen will cause it pickup the Search Context - SearchContext search = new SearchContext(); - - // set the full-text/name field value - search.setText(properties.getText()); - - // set whether to force AND operation on text terms - search.setForceAndTerms(Application.getClientConfig(FacesContext.getCurrentInstance()).getForceAndTerms()); - - if (properties.getMode().equals(MODE_ALL)) - { - search.setMode(SearchContext.SEARCH_ALL); - } - else if (properties.getMode().equals(MODE_FILES_TEXT)) - { - search.setMode(SearchContext.SEARCH_FILE_NAMES_CONTENTS); - } - else if (properties.getMode().equals(MODE_FILES)) - { - search.setMode(SearchContext.SEARCH_FILE_NAMES); - } - else if (properties.getMode().equals(MODE_FOLDERS)) - { - search.setMode(SearchContext.SEARCH_SPACE_NAMES); - } - - // additional attributes search - if (properties.getDescription() != null && properties.getDescription().length() != 0) - { - search.addAttributeQuery(ContentModel.PROP_DESCRIPTION, properties.getDescription()); - } - if (properties.getTitle() != null && properties.getTitle().length() != 0) - { - search.addAttributeQuery(ContentModel.PROP_TITLE, properties.getTitle()); - } - if (properties.getAuthor() != null && properties.getAuthor().length() != 0) - { - search.addAttributeQuery(ContentModel.PROP_AUTHOR, properties.getAuthor()); - } - if (properties.getContentFormat() != null && properties.getContentFormat().length() != 0) - { - search.setMimeType(properties.getContentFormat()); - } - if (properties.isCreatedDateChecked()) - { - SimpleDateFormat df = CachingDateFormat.getDateFormat(); - - Calendar cal = Calendar.getInstance(); - cal.setTime(properties.getCreatedDateFrom()); - cal.set(Calendar.HOUR_OF_DAY, cal.getMinimum(Calendar.HOUR_OF_DAY)); - cal.set(Calendar.MINUTE, cal.getMinimum(Calendar.MINUTE)); - cal.set(Calendar.SECOND, cal.getMinimum(Calendar.SECOND)); - cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND)); - String strCreatedDate = df.format(cal.getTime()); - - cal.setTime(properties.getCreatedDateTo()); - cal.set(Calendar.HOUR_OF_DAY, cal.getMinimum(Calendar.HOUR_OF_DAY)); - cal.set(Calendar.MINUTE, cal.getMinimum(Calendar.MINUTE)); - cal.set(Calendar.SECOND, cal.getMinimum(Calendar.SECOND)); - cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND)); - cal.add(Calendar.DAY_OF_YEAR, 1); - cal.add(Calendar.MILLISECOND, -1); - String strCreatedDateTo = df.format(cal.getTime()); - - search.addRangeQuery(ContentModel.PROP_CREATED, strCreatedDate, strCreatedDateTo, true); - } - if (properties.isModifiedDateChecked()) - { - SimpleDateFormat df = CachingDateFormat.getDateFormat(); - - Calendar cal = Calendar.getInstance(); - cal.setTime(properties.getModifiedDateFrom()); - cal.set(Calendar.HOUR_OF_DAY, cal.getMinimum(Calendar.HOUR_OF_DAY)); - cal.set(Calendar.MINUTE, cal.getMinimum(Calendar.MINUTE)); - cal.set(Calendar.SECOND, cal.getMinimum(Calendar.SECOND)); - cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND)); - String strModifiedDate = df.format(cal.getTime()); - - cal.setTime(properties.getModifiedDateTo()); - cal.set(Calendar.HOUR_OF_DAY, cal.getMinimum(Calendar.HOUR_OF_DAY)); - cal.set(Calendar.MINUTE, cal.getMinimum(Calendar.MINUTE)); - cal.set(Calendar.SECOND, cal.getMinimum(Calendar.SECOND)); - cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND)); - cal.add(Calendar.DAY_OF_YEAR, 1); - cal.add(Calendar.MILLISECOND, -1); - String strModifiedDateTo = df.format(cal.getTime()); - - search.addRangeQuery(ContentModel.PROP_MODIFIED, strModifiedDate, strModifiedDateTo, true); - } - - // in case of dynamic config, only lookup once - Map customPropertyLookup = getCustomPropertyLookup(); - - // walk each of the custom properties add add them as additional attributes - for (String qname : properties.getCustomProperties().keySet()) - { - Object value = properties.getCustomProperties().get(qname); - DataTypeDefinition typeDef = customPropertyLookup.get(qname); - if (typeDef != null) - { - QName typeName = typeDef.getName(); - if (DataTypeDefinition.DATE.equals(typeName) || DataTypeDefinition.DATETIME.equals(typeName)) - { - // only apply date to search if the user has checked the enable checkbox - if (value != null && Boolean.valueOf(value.toString()) == true) - { - SimpleDateFormat df = CachingDateFormat.getDateFormat(); - String strDateFrom = df.format(properties.getCustomProperties().get( - UISearchCustomProperties.PREFIX_DATE_FROM + qname)); - String strDateTo = df.format(properties.getCustomProperties().get( - UISearchCustomProperties.PREFIX_DATE_TO + qname)); - search.addRangeQuery(QName.createQName(qname), strDateFrom, strDateTo, true); - } - } - else if (DataTypeDefinition.BOOLEAN.equals(typeName)) - { - if (((Boolean)value) == true) - { - search.addFixedValueQuery(QName.createQName(qname), value.toString()); - } - } - else if (DataTypeDefinition.NODE_REF.equals(typeName) || DataTypeDefinition.CATEGORY.equals(typeName)) - { - if (value != null) - { - search.addFixedValueQuery(QName.createQName(qname), value.toString()); - } - } - else if (value != null) - { - // is the value from a list? - String strVal = value.toString(); - Object item = properties.getCustomProperties().get( - UISearchCustomProperties.PREFIX_LOV_ITEM + qname); - if (item != null) - { - // ListOfValues custom property - use a fixed value query if set - if (((Boolean)value) == true) - { - search.addFixedValueQuery(QName.createQName(qname), item.toString()); - } - } - else if (strVal != null && strVal.length() != 0) - { - if (DataTypeDefinition.INT.equals(typeName) || DataTypeDefinition.LONG.equals(typeName) || - DataTypeDefinition.FLOAT.equals(typeName) || DataTypeDefinition.DOUBLE.equals(typeName)) - { - search.addFixedValueQuery(QName.createQName(qname), strVal); - } - else - { - // by default use toString() value - this is for text fields and unknown types - search.addAttributeQuery(QName.createQName(qname), strVal); - } - } - } - } - } - - // location path search - if (properties.getLookin().equals(LOOKIN_OTHER) && properties.getLocation() != null) - { - search.setLocation(SearchContext.getPathFromSpaceRef(properties.getLocation(), properties.isLocationChildren())); - } - - // category path search - if (properties.getCategories().size() != 0) - { - String[] paths = new String[properties.getCategories().size()]; - for (int i=0; i getSavedSearches() - { - List savedSearches = properties.getCachedSavedSearches().get(); - if (savedSearches == null) - { - FacesContext fc = FacesContext.getCurrentInstance(); - ServiceRegistry services = Repository.getServiceRegistry(fc); - - // get the searches list from the current user or global searches location - NodeRef searchesRef = null; - if (SAVED_SEARCHES_USER.equals(properties.getSavedSearchMode()) == true) - { - searchesRef = getUserSearchesRef(); - } - else if (SAVED_SEARCHES_GLOBAL.equals(properties.getSavedSearchMode()) == true) - { - searchesRef = getGlobalSearchesRef(); - } - - // read the content nodes under the folder - if (searchesRef != null) - { - DictionaryService dd = services.getDictionaryService(); - - List childRefs = getNodeService().getChildAssocs( - searchesRef, - ContentModel.ASSOC_CONTAINS, - RegexQNamePattern.MATCH_ALL); - - savedSearches = new ArrayList(childRefs.size() + 1); - if (childRefs.size() != 0) - { - for (ChildAssociationRef ref : childRefs) - { - Node childNode = new Node(ref.getChildRef()); - if (dd.isSubClass(childNode.getType(), ContentModel.TYPE_CONTENT)) - { - savedSearches.add(new SelectItem(childNode.getId(), childNode.getName())); - } - } - - // make sure the list is sorted by the label - QuickSort sorter = new QuickSort(savedSearches, "label", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - } - } - else - { - // handle missing/access denied folder case - savedSearches = new ArrayList(1); - } - - // add an entry (at the start) to instruct the user to select a saved search - savedSearches.add(0, new SelectItem(NO_SELECTION, - Application.getMessage(FacesContext.getCurrentInstance(), MSG_SELECT_SAVED_SEARCH))); - - // store in the cache (will auto-expire) - properties.getCachedSavedSearches().put(savedSearches); - } - - return savedSearches; - } - - /** - * Change the current saved searches list mode based on user selection - */ - public void savedSearchModeChanged(ActionEvent event) - { - UIModeList savedModeList = (UIModeList)event.getComponent(); - - // get the saved searches list mode - String viewMode = savedModeList.getValue().toString(); - - // persist - properties.setSavedSearchMode(viewMode); - - // clear existing caches and values - // the values will be re-queried when the client requests the saved searches list - properties.getCachedSavedSearches().clear(); - properties.setSavedSearch(null); - } - - /** - * Action handler called when a saved search is selected by the user - */ - public void selectSearch(ActionEvent event) - { - if (NO_SELECTION.equals(properties.getSavedSearch()) == false) - { - // read an XML serialized version of the SearchContext object - NodeRef searchSearchRef = new NodeRef(Repository.getStoreRef(), properties.getSavedSearch()); - ServiceRegistry services = Repository.getServiceRegistry(FacesContext.getCurrentInstance()); - ContentService cs = services.getContentService(); - try - { - if (services.getNodeService().exists(searchSearchRef)) - { - ContentReader reader = cs.getReader(searchSearchRef, ContentModel.PROP_CONTENT); - SearchContext search = new SearchContext().fromXML(reader.getContentString()); - - // if we get here we read the serialized object successfully - // now setup the UI to match the new SearchContext object - initialiseFromContext(search); - } - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), MSG_ERROR_RESTORE_SEARCH), err.getMessage()), err); - } - } - } - - /** - * Initialise the Advanced Search UI screen from a SearchContext - * - * @param search the SearchContext to retrieve state from - */ - private void initialiseFromContext(SearchContext search) - { - resetFields(); - - properties.setText(search.getText()); - - switch (search.getMode()) - { - case SearchContext.SEARCH_ALL: - properties.setMode(MODE_ALL); - break; - case SearchContext.SEARCH_FILE_NAMES_CONTENTS: - properties.setMode(MODE_FILES_TEXT); - break; - case SearchContext.SEARCH_FILE_NAMES: - properties.setMode(MODE_FILES); - break; - case SearchContext.SEARCH_SPACE_NAMES: - properties.setMode(MODE_FOLDERS); - break; - } - properties.getPanels().put(PANEL_RESTRICT, true); - - if (search.getLocation() != null) - { - properties.setLocationChildren(search.getLocation().endsWith("//*")); - properties.setLocation(findNodeRefFromPath(search.getLocation())); - properties.setLookin(LOOKIN_OTHER); - properties.getPanels().put(PANEL_LOCATION, true); - } - - String[] categories = search.getCategories(); - if (categories != null && categories.length != 0) - { - for (String category : categories) - { - NodeRef categoryRef = findNodeRefFromPath(category); - if (categoryRef != null) - { - Node categoryNode = new MapNode(categoryRef); - // add a value bound propery used to indicate if searching across children is selected - categoryNode.getProperties().put(INCLUDE_CHILDREN, category.endsWith("//*")); - properties.getCategories().add(categoryNode); - } - } - properties.getPanels().put(PANEL_CATEGORIES, true); - } - - properties.setContentType(search.getContentType()); - properties.setContentFormat(search.getMimeType()); - properties.setFolderType(search.getFolderType()); - - properties.setDescription(search.getAttributeQuery(ContentModel.PROP_DESCRIPTION)); - properties.setTitle(search.getAttributeQuery(ContentModel.PROP_TITLE)); - properties.setAuthor(search.getAttributeQuery(ContentModel.PROP_AUTHOR)); - if (properties.getContentType() != null || properties.getContentFormat() != null || - properties.getDescription() != null || properties.getTitle() != null || - properties.getAuthor() != null) - { - properties.getPanels().put(PANEL_ATTRS, true); - } - - RangeProperties createdDate = search.getRangeProperty(ContentModel.PROP_CREATED); - if (createdDate != null) - { - properties.setCreatedDateFrom(Utils.parseXMLDateFormat(createdDate.lower)); - properties.setCreatedDateTo(Utils.parseXMLDateFormat(createdDate.upper)); - properties.setCreatedDateChecked(true); - properties.getPanels().put(PANEL_ATTRS, true); - } - RangeProperties modifiedDate = search.getRangeProperty(ContentModel.PROP_MODIFIED); - if (modifiedDate != null) - { - properties.setModifiedDateFrom(Utils.parseXMLDateFormat(modifiedDate.lower)); - properties.setModifiedDateTo(Utils.parseXMLDateFormat(modifiedDate.upper)); - properties.setModifiedDateChecked(true); - properties.getPanels().put(PANEL_ATTRS, true); - } - - // in case of dynamic config, only lookup once - Map customPropertyLookup = getCustomPropertyLookup(); - - // custom fields - calculate which are required to set through the custom properties lookup table - for (String qname : customPropertyLookup.keySet()) - { - DataTypeDefinition typeDef = customPropertyLookup.get(qname); - if (typeDef != null) - { - QName typeName = typeDef.getName(); - if (DataTypeDefinition.DATE.equals(typeName) || DataTypeDefinition.DATETIME.equals(typeName)) - { - RangeProperties dateProps = search.getRangeProperty(QName.createQName(qname)); - if (dateProps != null) - { - properties.getCustomProperties().put(UISearchCustomProperties.PREFIX_DATE_FROM + qname, - Utils.parseXMLDateFormat(dateProps.lower)); - properties.getCustomProperties().put(UISearchCustomProperties.PREFIX_DATE_TO + qname, - Utils.parseXMLDateFormat(dateProps.upper)); - properties.getCustomProperties().put(qname, true); - properties.getPanels().put(PANEL_CUSTOM, true); - } - } - else if (DataTypeDefinition.BOOLEAN.equals(typeName)) - { - String strBool = search.getFixedValueQuery(QName.createQName(qname)); - if (strBool != null) - { - properties.getCustomProperties().put(qname, Boolean.parseBoolean(strBool)); - properties.getPanels().put(PANEL_CUSTOM, true); - } - } - else if (DataTypeDefinition.NODE_REF.equals(typeName) || DataTypeDefinition.CATEGORY.equals(typeName)) - { - String strNodeRef = search.getFixedValueQuery(QName.createQName(qname)); - if (strNodeRef != null) - { - properties.getCustomProperties().put(qname, new NodeRef(strNodeRef)); - properties.getPanels().put(PANEL_CUSTOM, true); - } - } - else if (DataTypeDefinition.INT.equals(typeName) || DataTypeDefinition.LONG.equals(typeName) || - DataTypeDefinition.FLOAT.equals(typeName) || DataTypeDefinition.DOUBLE.equals(typeName)) - { - // currently numbers are rendered as text in UISearchCustomProperties component - // this code will need updating if that changes! - properties.getCustomProperties().put(qname, search.getFixedValueQuery(QName.createQName(qname))); - properties.getPanels().put(PANEL_CUSTOM, true); - } - else - { - // a default datatype may indicate either an attribute query, or if a Fixed Value - // is present then it's a LOV constraint with a value selected - Object value = search.getFixedValueQuery(QName.createQName(qname)); - if (value != null) - { - properties.getCustomProperties().put(UISearchCustomProperties.PREFIX_LOV_ITEM + qname, value); - properties.getCustomProperties().put(qname, Boolean.TRUE); - } - else - { - properties.getCustomProperties().put(qname, search.getAttributeQuery(QName.createQName(qname))); - } - properties.getPanels().put(PANEL_CUSTOM, true); - } - } - } - } - - /** - * Return NodeRef to the last Node referenced on the end of the specified xpath value - * - * @param xpath XPath - note that any /* or //* will be removed to find trailing node - * - * @return NodeRef if found null otherwise - */ - private NodeRef findNodeRefFromPath(String xpath) - { - if (xpath.endsWith("//*")) - { - xpath = xpath.substring(0, xpath.lastIndexOf("//*")); - } - else if (xpath.endsWith("/*")) - { - xpath = xpath.substring(0, xpath.lastIndexOf("/*")); - } - NodeRef rootRef = new NodeRef(Repository.getStoreRef(), Application.getCompanyRootId(FacesContext.getCurrentInstance())); - List results = null; - try - { - results = getSearchService().selectNodes( - rootRef, - xpath, - null, - getNamespaceService(), - false); - } - catch (AccessDeniedException err) - { - // ignore and return null - } - - return (results != null && results.size() == 1) ? results.get(0) : null; - } - - /** - * @return the cached reference to the shared Saved Searches folder - */ - protected NodeRef getUserSearchesRef() - { - if (properties.getUserSearchesRef() == null) - { - NodeRef globalRef = getGlobalSearchesRef(); - if (globalRef != null) - { - FacesContext fc = FacesContext.getCurrentInstance(); - User user = Application.getCurrentUser(fc); - String userName = ISO9075.encode(user.getUserName()); - String xpath = NamespaceService.APP_MODEL_PREFIX + ":" + QName.createValidLocalName(userName); - - List results = null; - try - { - results = getSearchService().selectNodes( - globalRef, - xpath, - null, - getNamespaceService(), - false); - } - catch (AccessDeniedException err) - { - // ignore and return null - } - - if (results != null) - { - if (results.size() == 1) - { - properties.setUserSearchesRef(results.get(0)); - } - else if (results.size() == 0 && new Node(globalRef).hasPermission(PermissionService.ADD_CHILDREN)) - { - // attempt to create folder for this user for first time - // create the preferences Node for this user - ChildAssociationRef childRef = getNodeService().createNode( - globalRef, - ContentModel.ASSOC_CONTAINS, - QName.createQName(NamespaceService.APP_MODEL_1_0_URI, QName.createValidLocalName(user.getUserName())), - ContentModel.TYPE_FOLDER, - null); - - properties.setUserSearchesRef(childRef.getChildRef()); - } - } - } - } - - return properties.getUserSearchesRef(); - } - - /** - * @return the cached reference to the global Saved Searches folder - */ - protected NodeRef getGlobalSearchesRef() - { - if (properties.getGlobalSearchesRef() == null) - { - FacesContext fc = FacesContext.getCurrentInstance(); - String xpath = Application.getRootPath(fc) + "/" + - Application.getGlossaryFolderName(fc) + "/" + - Application.getSavedSearchesFolderName(fc); - - List results = null; - try - { - results = getSearchService().selectNodes( - getNodeService().getRootNode(Repository.getStoreRef()), - xpath, - null, - getNamespaceService(), - false); - } - catch (AccessDeniedException err) - { - // ignore and return null - } - - if (results != null && results.size() == 1) - { - properties.setGlobalSearchesRef(results.get(0)); - } - } - - return properties.getGlobalSearchesRef(); - } - - /** - * Action handler called when the Add button is pressed to add the current Category selection - */ - @SuppressWarnings("unchecked") - public void addCategory(ActionEvent event) - { - UIAjaxCategoryPicker selector = (UIAjaxCategoryPicker)event.getComponent().findComponent("catSelector"); - UISelectBoolean chkChildren = (UISelectBoolean)event.getComponent().findComponent("chkCatChildren"); - - List categoryRefs = (List)selector.getValue(); - if (categoryRefs != null) - { - for (NodeRef categoryRef : categoryRefs) - { - Node categoryNode = new MapNode(categoryRef); - // add a value bound propery used to indicate if searching across children is selected - categoryNode.getProperties().put(INCLUDE_CHILDREN, chkChildren.isSelected()); - properties.getCategories().add(categoryNode); - } - // clear selector value after the list has been populated - selector.setValue(null); - } - } - - /** - * Action handler called when the Remove button is pressed to remove a category - */ - public void removeCategory(ActionEvent event) - { - Node node = (Node) properties.getCategoriesDataModel().getRowData(); - if (node != null) - { - properties.getCategories().remove(node); - } - } - - /** - * @return ClientConfigElement - */ - private AdvancedSearchConfigElement getSearchConfig() - { - if (properties.getSearchConfigElement() == null) - { - properties.setSearchConfigElement((AdvancedSearchConfigElement)Application.getConfigService( - FacesContext.getCurrentInstance()).getConfig("Advanced Search"). - getConfigElement(AdvancedSearchConfigElement.CONFIG_ELEMENT_ID)); - } - - return properties.getSearchConfigElement(); - } - - /** - * Helper map to lookup custom property QName strings against a DataTypeDefinition - * - * @return custom property lookup Map - */ - private Map getCustomPropertyLookup() - { - if ((properties.getCustomPropertyLookup() == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - properties.setCustomPropertyLookup(new HashMap(7, 1.0f)); - List customProps = getSearchConfig().getCustomProperties(); - if (customProps != null) - { - DictionaryService dd = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getDictionaryService(); - for (CustomProperty customProp : customProps) - { - PropertyDefinition propDef = null; - QName propQName = Repository.resolveToQName(customProp.Property); - if (customProp.Type != null) - { - QName type = Repository.resolveToQName(customProp.Type); - TypeDefinition typeDef = dd.getType(type); - propDef = typeDef.getProperties().get(propQName); - } - else if (customProp.Aspect != null) - { - QName aspect = Repository.resolveToQName(customProp.Aspect); - AspectDefinition aspectDef = dd.getAspect(aspect); - propDef = aspectDef.getProperties().get(propQName); - } - - if (propQName != null && propDef != null) - { - properties.getCustomPropertyLookup().put(propQName.toString(), propDef.getDataType()); - } - } - } - } - return properties.getCustomPropertyLookup(); - } - - /** - * Save the state of the progressive panel that was expanded/collapsed - */ - public void expandPanel(ActionEvent event) - { - if (event instanceof ExpandedEvent) - { - properties.getPanels().put(event.getComponent().getId(), ((ExpandedEvent) event).State); - } - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_SAVE); - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - - // ------------------------------------------------------------------------------ - // Private data - - protected SearchProperties properties; - - private static final String MSG_ALL_FORMATS = "all_formats"; - private static final String MSG_ERROR_RESTORE_SEARCH = "error_restore_search"; - private static final String MSG_SELECT_SAVED_SEARCH = "select_saved_search"; - private static final String MSG_SAVE = "save"; - - private static final String OUTCOME_BROWSE = "browse"; - - private static final String PANEL_CUSTOM = "custom-panel"; - private static final String PANEL_ATTRS = "attrs-panel"; - private static final String PANEL_CATEGORIES = "categories-panel"; - private static final String PANEL_RESTRICT = "restrict-panel"; - private static final String PANEL_LOCATION = "location-panel"; - - private static final String INCLUDE_CHILDREN = "includeChildren"; - - private static final String MODE_ALL = "all"; - private static final String MODE_FILES_TEXT = "files_text"; - private static final String MODE_FILES = "files"; - private static final String MODE_FOLDERS = "folders"; - - private static final String LOOKIN_ALL = "all"; - private static final String LOOKIN_OTHER = "other"; - - private static final String SAVED_SEARCHES_USER = "user"; - private static final String SAVED_SEARCHES_GLOBAL = "global"; - - private static final String NO_SELECTION = "NONE"; -} diff --git a/war/src/main/java/org/alfresco/web/bean/search/EditSearchDialog.java b/war/src/main/java/org/alfresco/web/bean/search/EditSearchDialog.java deleted file mode 100644 index 66784a1706..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/search/EditSearchDialog.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.search; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.service.cmr.repository.ContentService; -import org.alfresco.service.cmr.repository.ContentWriter; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; - -public class EditSearchDialog extends AdvancedSearchDialog -{ - private static final long serialVersionUID = -8914819218709478527L; - - private static final String MSG_ERROR_SAVE_SEARCH = "error_save_search"; - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return saveEditSearchOK(context, outcome); - } - - @Override - public String getFinishButtonLabel() - { - return super.getFinishButtonLabel(); - } - - public String saveEditSearchOK(FacesContext newContext, String newOutcome) - { - String outcome = newOutcome; - - final SearchContext search = this.navigator.getSearchContext(); - if (search != null) - { - try - { - final FacesContext context = newContext; - - RetryingTransactionCallback callback = new RetryingTransactionCallback() - { - public Object execute() throws Throwable - { - // handle Edit e.g. Overwrite of existing search - // detect if was previously selected saved search (e.g. - // NodeRef not null) - NodeRef searchRef = new NodeRef(Repository.getStoreRef(), properties.getSavedSearch()); - if (getNodeService().exists(searchRef)) - { - Map props = getNodeService().getProperties(searchRef); - props.put(ContentModel.PROP_NAME, properties.getSearchName()); - props.put(ContentModel.PROP_DESCRIPTION, properties.getSearchDescription()); - getNodeService().setProperties(searchRef, props); - - ContentService contentService = Repository.getServiceRegistry(context).getContentService(); - ContentWriter writer = contentService.getWriter(searchRef, ContentModel.PROP_CONTENT, true); - - // get a writer to our new node ready for XML - // content - writer.setMimetype(MimetypeMap.MIMETYPE_XML); - writer.setEncoding("UTF-8"); - - // output an XML serialized version of the - // SearchContext object - writer.putContent(search.toXML()); - } - return null; - } - }; - callback.execute(); - - properties.getCachedSavedSearches().clear(); - properties.setSavedSearch(null); - } - catch (Throwable e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(newContext, MSG_ERROR_SAVE_SEARCH), e.getMessage()), e); - outcome = null; - this.isFinished = false; - ReportedException.throwIfNecessary(e); - } - } - - return outcome; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/search/SaveSearchDialog.java b/war/src/main/java/org/alfresco/web/bean/search/SaveSearchDialog.java deleted file mode 100644 index dbd9e382c3..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/search/SaveSearchDialog.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.search; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.HashMap; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.ContentService; -import org.alfresco.service.cmr.repository.ContentWriter; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; - -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; - -public class SaveSearchDialog extends AdvancedSearchDialog -{ - - private static final long serialVersionUID = 237262751601280456L; - - private static final String MSG_ERROR_SAVE_SEARCH = "error_save_search"; - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return saveNewSearchOK(context, outcome); - } - - @Override - public String getFinishButtonLabel() - { - return super.getFinishButtonLabel(); - } - - public String saveNewSearchOK(FacesContext newContext, String newOutcome) - { - String outcome = newOutcome; - - NodeRef searchesRef; - if (properties.isSearchSaveGlobal()) - { - searchesRef = getGlobalSearchesRef(); - } - else - { - searchesRef = getUserSearchesRef(); - } - - final SearchContext search = this.navigator.getSearchContext(); - if (searchesRef != null && search != null) - { - try - { - final FacesContext context = newContext;// FacesContext.getCurrentInstance(); - final NodeRef searchesRefFinal = searchesRef; - - RetryingTransactionCallback callback = new RetryingTransactionCallback() - { - public Object execute() throws Throwable - { - // create new content node as the saved search object - Map props = new HashMap(2, 1.0f); - props.put(ContentModel.PROP_NAME, properties.getSearchName()); - props.put(ContentModel.PROP_DESCRIPTION, properties.getSearchDescription()); - ChildAssociationRef childRef = getNodeService().createNode(searchesRefFinal, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.ALFRESCO_URI, QName - .createValidLocalName(properties.getSearchName())), ContentModel.TYPE_CONTENT, props); - - ContentService contentService = Repository.getServiceRegistry(context).getContentService(); - ContentWriter writer = contentService.getWriter(childRef.getChildRef(), ContentModel.PROP_CONTENT, true); - - // get a writer to our new node ready for XML content - writer.setMimetype(MimetypeMap.MIMETYPE_XML); - writer.setEncoding("UTF-8"); - - // output an XML serialized version of the SearchContext - // object - writer.putContent(search.toXML()); - return null; - } - }; - callback.execute(); - properties.getCachedSavedSearches().clear(); - properties.setSavedSearch(null); - } - catch (Throwable e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(newContext, MSG_ERROR_SAVE_SEARCH), e.getMessage()), e); - outcome = null; - this.isFinished = false; - ReportedException.throwIfNecessary(e); - } - } - - return outcome; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/search/SearchContext.java b/war/src/main/java/org/alfresco/web/bean/search/SearchContext.java deleted file mode 100644 index e03b57b29f..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/search/SearchContext.java +++ /dev/null @@ -1,1090 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.search; - -import java.io.Serializable; -import java.io.StringReader; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.StringTokenizer; - -import javax.faces.context.FacesContext; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.Path; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.util.ISO9075; -import org.alfresco.util.SearchLanguageConversion; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Repository; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.dom4j.Document; -import org.dom4j.DocumentHelper; -import org.dom4j.Element; -import org.dom4j.io.OutputFormat; -import org.dom4j.io.SAXReader; -import org.dom4j.io.XMLWriter; - -/** - * Holds the context required to build a search query and can return the populated query. - *

- * Builds a lucene format search string from each of the supplied attributes and terms. - * Can be serialized to and from XML format for saving and restoring of previous searches. - * - * @author Kevin Roast - */ -public class SearchContext implements Serializable -{ - private static final long serialVersionUID = 6730844584074229969L; - - /** XML serialization elements */ - private static final String ELEMENT_VALUE = "value"; - private static final String ELEMENT_FIXED_VALUES = "fixed-values"; - private static final String ELEMENT_INCLUSIVE = "inclusive"; - private static final String ELEMENT_UPPER = "upper"; - private static final String ELEMENT_LOWER = "lower"; - private static final String ELEMENT_RANGE = "range"; - private static final String ELEMENT_RANGES = "ranges"; - private static final String ELEMENT_NAME = "name"; - private static final String ELEMENT_ATTRIBUTE = "attribute"; - private static final String ELEMENT_ATTRIBUTES = "attributes"; - private static final String ELEMENT_MIMETYPE = "mimetype"; - private static final String ELEMENT_CONTENT_TYPE = "content-type"; - private static final String ELEMENT_FOLDER_TYPE = "folder-type"; - private static final String ELEMENT_CATEGORY = "category"; - private static final String ELEMENT_CATEGORIES = "categories"; - private static final String ELEMENT_LOCATION = "location"; - private static final String ELEMENT_MODE = "mode"; - private static final String ELEMENT_TEXT = "text"; - private static final String ELEMENT_SEARCH = "search"; - private static final String ELEMENT_QUERY = "query"; - - /** advanced search term operators */ - private static final char OP_WILDCARD = '*'; - private static final char OP_AND = '+'; - private static final char OP_NOT = '-'; - private static final String STR_OP_WILDCARD = "" + OP_WILDCARD; - - /** Search mode constants */ - public final static int SEARCH_ALL = 0; - public final static int SEARCH_FILE_NAMES_CONTENTS = 1; - public final static int SEARCH_FILE_NAMES = 2; - public final static int SEARCH_SPACE_NAMES = 3; - - /** the search text string */ - private String text = ""; - - /** mode for the search */ - private int mode = SearchContext.SEARCH_ALL; - - /** folder XPath location for the search */ - private String location = null; - - /** categories to add to the search */ - private String[] categories = new String[0]; - - /** folder type to restrict search against */ - private String folderType = null; - - /** content type to restrict search against */ - private String contentType = null; - - /** content mimetype to restrict search against */ - private String mimeType = null; - - /** any extra simple query attributes to add to the search */ - protected List simpleSearchAdditionalAttrs = new ArrayList(4); - - /** any extra query attributes to add to the search */ - private Map queryAttributes = new HashMap(5, 1.0f); - - /** any additional range attribute to add to the search */ - private Map rangeAttributes = new HashMap(5, 1.0f); - - /** any additional fixed value attributes to add to the search, such as boolean or noderef */ - private Map queryFixedValues = new HashMap(5, 1.0f); - - /** set true to force the use of AND between text terms */ - private boolean forceAndTerms = false; - - /** logger */ - private static Log logger = LogFactory.getLog(SearchContext.class); - - - /** - * Build the search query string based on the current search context members. - * - * @param minimum small possible textual string used for a match - * this does not effect fixed values searches (e.g. boolean, int values) or date ranges - * - * @return prepared search query string - */ - public String buildQuery(int minimum) - { - String query; - boolean validQuery = false; - - // the QName for the well known "name" attribute - String nameAttr = Repository.escapeQName(QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, ELEMENT_NAME)); - - StringBuilder plBuf = new StringBuilder(500).append("("); - StringBuilder mnBuf = new StringBuilder(500).append("-("); - - // match against content text - String text = this.text.trim(); - boolean appendText = mode == SEARCH_FILE_NAMES_CONTENTS || mode == SEARCH_ALL; - - if (text.length() != 0 && text.length() >= minimum) - { - if (text.indexOf(' ') == -1 && text.charAt(0) != '"') - { - // check for existance of a special operator - boolean operatorAND = (text.charAt(0) == OP_AND); - boolean operatorNOT = (text.charAt(0) == OP_NOT); - // strip operator from term if one was found - if (operatorAND || operatorNOT) - { - text = text.substring(1); - } - - if (text.length() != 0) - { - if (operatorNOT) - { - processSearchTextAttribute(nameAttr, text, appendText, mnBuf); - processSearchAdditionalAttributes(text, mnBuf, this.simpleSearchAdditionalAttrs); - } - else - { - if (plBuf.length() > 1) - { - plBuf.append(' '); - } - if (operatorAND) - { - plBuf.append(OP_AND); - } - plBuf.append('('); - processSearchTextAttribute(nameAttr, text, appendText, plBuf); - processSearchAdditionalAttributes(text, plBuf, this.simpleSearchAdditionalAttrs); - plBuf.append(')'); - } - } - } - else - { - // multiple word search - if (text.charAt(0) == '"' && text.charAt(text.length() - 1) == '"') - { - // as a single quoted phrase - String quotedSafeText = '"' + SearchLanguageConversion.escapeLuceneQuery(text.substring(1, text.length() - 1)) + '"'; - if (appendText) - { - plBuf.append("TEXT:").append(quotedSafeText); - } - plBuf.append(" @").append(nameAttr).append(":").append(quotedSafeText); - for (QName qname : this.simpleSearchAdditionalAttrs) - { - plBuf.append(" @").append( - Repository.escapeQName(qname)).append(":").append(quotedSafeText); - } - } - else - { - // as individual search terms - StringTokenizer t = new StringTokenizer(text, " "); - - int tokenCount = t.countTokens(); - for (int i=0; i 0) - { - plBuf.append(' '); - } - if (operatorAND) - { - plBuf.append(OP_AND); - } - plBuf.append('('); - processSearchTextAttribute(nameAttr, term, appendText, plBuf); - if (mode == SearchContext.SEARCH_ALL) - { - processSearchAdditionalAttributes(term, plBuf, this.simpleSearchAdditionalAttrs); - } - plBuf.append(')'); - } - } - } - } - } - - plBuf.append(')'); - mnBuf.append(')'); - - validQuery = true; - } - - // match a specific PATH for space location or categories - StringBuilder pathQuery = null; - if (location != null || (categories != null && categories.length !=0)) - { - pathQuery = new StringBuilder(128); - if (location != null) - { - pathQuery.append(" PATH:\"").append(location).append("\" "); - if (categories != null && categories.length != 0) - { - pathQuery.append("AND ("); - } - } - if (categories != null && categories.length != 0) - { - for (int i=0; i= minimum) - { - processSearchAttribute(qname, value, attributeQuery); - } - } - - // handle the case where we did not add any attributes due to minimum length restrictions - if (attributeQuery.length() == 0) - { - attributeQuery = null; - } - } - - // match any extra fixed value attributes specified - if (queryFixedValues.size() != 0) - { - if (attributeQuery == null) - { - attributeQuery = new StringBuilder(queryFixedValues.size() << 6); - } - for (QName qname : queryFixedValues.keySet()) - { - String escapedName = Repository.escapeQName(qname); - String value = queryFixedValues.get(qname); - attributeQuery.append(" +@").append(escapedName) - .append(":\"").append(SearchLanguageConversion.escapeLuceneQuery(value)).append('"'); - } - } - - // range attributes are a special case also - if (rangeAttributes.size() != 0) - { - if (attributeQuery == null) - { - attributeQuery = new StringBuilder(rangeAttributes.size() << 6); - } - for (QName qname : rangeAttributes.keySet()) - { - String escapedName = Repository.escapeQName(qname); - RangeProperties rp = rangeAttributes.get(qname); - String value1 = SearchLanguageConversion.escapeLuceneQuery(rp.lower); - String value2 = SearchLanguageConversion.escapeLuceneQuery(rp.upper); - attributeQuery.append(" +@").append(escapedName) - .append(":").append(rp.inclusive ? "[" : "{").append(value1) - .append(" TO ").append(value2).append(rp.inclusive ? "]" : "}"); - } - } - - // mimetype is a special case - it is indexed as a special attribute it comes from the combined - // ContentData attribute of cm:content - ContentData string cannot be searched directly - if (mimeType != null && mimeType.length() != 0) - { - if (attributeQuery == null) - { - attributeQuery = new StringBuilder(64); - } - String escapedName = Repository.escapeQName(QName.createQName(ContentModel.PROP_CONTENT + ".mimetype")); - attributeQuery.append(" +@").append(escapedName) - .append(":").append(mimeType); - } - - // match against appropriate content type - String fileTypeQuery; - if (contentType != null) - { - fileTypeQuery = " TYPE:\"" + contentType + "\" "; - } - else - { - // default to cm:content - fileTypeQuery = " TYPE:\"{" + NamespaceService.CONTENT_MODEL_1_0_URI + "}content\" "; - } - - // match against appropriate folder type - String folderTypeQuery; - if (folderType != null) - { - folderTypeQuery = " TYPE:\"" + folderType + "\" "; - } - else - { - folderTypeQuery = " TYPE:\"{" + NamespaceService.CONTENT_MODEL_1_0_URI + "}folder\" "; - } - - if (text.length() != 0 && text.length() >= minimum) - { - StringBuilder buf = new StringBuilder(128); - if (plBuf.length() > 2) - { - buf.append(plBuf); - if (mnBuf.length() > 3) - { - buf.append(" AND "); - } - } - if (mnBuf.length() > 3) - { - buf.append(mnBuf); - } - // text query for name and/or full text specified - switch (mode) - { - case SearchContext.SEARCH_ALL: - query = '(' + fileTypeQuery + " AND " + '(' + buf + ')' + ')' + - ' ' + - '(' + folderTypeQuery + " AND " + '(' + buf + "))"; - break; - - case SearchContext.SEARCH_FILE_NAMES: - case SearchContext.SEARCH_FILE_NAMES_CONTENTS: - query = fileTypeQuery + " AND " + '(' + buf + ')'; - break; - - case SearchContext.SEARCH_SPACE_NAMES: - query = folderTypeQuery + " AND " + buf; - break; - - default: - throw new IllegalStateException("Unknown search mode specified: " + mode); - } - } - else - { - // no text query specified - must be an attribute/value query only - switch (mode) - { - case SearchContext.SEARCH_ALL: - query = '(' + fileTypeQuery + ' ' + folderTypeQuery + ')'; - break; - - case SearchContext.SEARCH_FILE_NAMES: - case SearchContext.SEARCH_FILE_NAMES_CONTENTS: - query = fileTypeQuery; - break; - - case SearchContext.SEARCH_SPACE_NAMES: - query = folderTypeQuery; - break; - - default: - throw new IllegalStateException("Unknown search mode specified: " + mode); - } - } - - // match entire query against any additional attributes specified - if (attributeQuery != null) - { - query = attributeQuery + " AND (" + query + ')'; - } - - // match entire query against any specified paths - if (pathQuery != null) - { - query = "(" + pathQuery + ") AND (" + query + ')'; - } - - query = "(" + query + ") AND NOT ASPECT:\"sys:hidden\" "; - - // check that we have a query worth executing - if we have no attributes, paths or text/name search - // then we'll only have a search against files/type TYPE which does nothing by itself! - validQuery = validQuery | (attributeQuery != null) | (pathQuery != null); - if (validQuery == false) - { - query = null; - } - - if (logger.isDebugEnabled()) - logger.debug("Query:\r\n" + query); - - return query; - } - - /** - * Build the lucene search terms required for the specified attribute and append to a buffer. - * Supports text values with a wildcard '*' character as the prefix and/or the suffix. - * - * @param qname QName of the attribute - * @param value Non-null value of the attribute - * @param buf Buffer to append lucene terms to - */ - private static void processSearchAttribute(QName qname, String value, StringBuilder buf) - { - buf.append(" +@").append(Repository.escapeQName(qname)).append(":\"") - .append(SearchContext.escape(value)).append("\" "); - } - - /** - * Build the lucene search terms required for the specified attribute and append to multiple buffers. - * Supports text values with a wildcard '*' character as the prefix and/or the suffix. - * - * @param qname QName.toString() of the attribute - * @param value Non-null value of the attribute - * @param appendText Attribute search buffer to append lucene terms to - * @param mnBuf Text search buffer to append lucene terms to - */ - private static void processSearchTextAttribute(String qname, String value, boolean appendText, StringBuilder mnBuf) - { - mnBuf.append('@').append(qname).append(":\"") - .append(SearchContext.escape(value)).append('"'); - if (appendText) - { - mnBuf.append(" TEXT:\"").append(SearchContext.escape(value)).append("\" "); - } - } - - private static void processSearchAdditionalAttributes(String value, StringBuilder buf, - List simpleSearchAdditionalAttrs) - { - for (QName qname : simpleSearchAdditionalAttrs) - { - buf.append(" @").append(Repository.escapeQName(qname)).append(":\"").append(SearchContext.escape(value)) - .append("\" "); - } - } - - /** - * Returns a String where those characters that QueryParser - * expects to be escaped are escaped by a preceding \. - * '*' and '?' are not escaped. - */ - private static String escape(String s) - { - StringBuffer sb = new StringBuffer(s.length() + 4); - for (int i = 0; i < s.length(); i++) - { - char c = s.charAt(i); - if (c == '\\' || c == '+' || c == '-' || c == '!' || c == '(' || c == ')' || c == ':' || - c == '^' || c == '[' || c == ']' || c == '\"' || c == '{' || c == '}' || c == '~') - { - sb.append('\\'); - } - sb.append(c); - } - return sb.toString(); - } - - /** - * Generate a search XPATH pointing to the specified node, optionally return an XPATH - * that includes the child nodes. - * - * @param ref Of the node to generate path too - * @param children Whether to include children of the node - * - * @return the path - */ - public static String getPathFromSpaceRef(NodeRef ref, boolean children) - { - FacesContext context = FacesContext.getCurrentInstance(); - Path path = Repository.getServiceRegistry(context).getNodeService().getPath(ref); - NamespaceService ns = Repository.getServiceRegistry(context).getNamespaceService(); - StringBuilder buf = new StringBuilder(64); - for (int i=0; i prefixes = ns.getPrefixes(elementRef.getQName().getNamespaceURI()); - if (prefixes.size() >0) - { - elementString = '/' + (String)prefixes.iterator().next() + ':' + ISO9075.encode(elementRef.getQName().getLocalName()); - } - } - } - - buf.append(elementString); - } - if (children == true) - { - // append syntax to get all children of the path - buf.append("//*"); - } - else - { - // append syntax to just represent the path, not the children - buf.append("/*"); - } - - return buf.toString(); - } - - /** - * @return Returns the categories to use for the search - */ - public String[] getCategories() - { - return this.categories; - } - - /** - * @param categories The categories to set as a list of search XPATHs - */ - public void setCategories(String[] categories) - { - if (categories != null) - { - this.categories = categories; - } - } - - /** - * @return Returns the node XPath to search in or null for all. - */ - public String getLocation() - { - return this.location; - } - - /** - * @param location The node XPATH to search from or null for all.. - */ - public void setLocation(String location) - { - this.location = location; - } - - /** - * @return Returns the mode to use during the search (see constants) - */ - public int getMode() - { - return this.mode; - } - - /** - * @param mode The mode to use during the search (see constants) - */ - public void setMode(int mode) - { - this.mode = mode; - } - - public String getSearchText() - { - if (this.text != null && this.text.trim().length() > 0) - { - return getText(); - } - StringBuilder res = new StringBuilder(); - for (QName attrName : this.queryAttributes.keySet()) - { - if (ContentModel.PROP_TITLE.isMatch(attrName)) - { - res.append(res.length() > 0 ? ", " : ""); - res.append(Application.getMessage(FacesContext.getCurrentInstance(), "title")); - res.append(": "); - res.append(this.queryAttributes.get(attrName)); - } - else if (ContentModel.PROP_DESCRIPTION.isMatch(attrName)) - { - res.append(res.length() > 0 ? ", " : ""); - res.append(Application.getMessage(FacesContext.getCurrentInstance(), "description")); - res.append(": "); - res.append(this.queryAttributes.get(attrName)); - } - else if (ContentModel.PROP_AUTHOR.isMatch(attrName)) - { - res.append(res.length() > 0 ? ", " : ""); - res.append(Application.getMessage(FacesContext.getCurrentInstance(), "author")); - res.append(": "); - res.append(this.queryAttributes.get(attrName)); - } - else - { - res.append(res.length() > 0 ? ", " : ""); - res.append(this.queryAttributes.get(attrName)); - } - } - return res.toString(); - } - - /** - * @return Returns the search text string. - */ - public String getText() - { - return this.text; - } - - /** - * @param text The search text string. - */ - public void setText(String text) - { - this.text = text; - } - - /** - * @return Returns the contentType. - */ - public String getContentType() - { - return this.contentType; - } - - /** - * @param contentType The content type to restrict attribute search against. - */ - public void setContentType(String contentType) - { - this.contentType = contentType; - } - - /** - * @return Returns the folderType. - */ - public String getFolderType() - { - return this.folderType; - } - - /** - * @param folderType The folder type to restrict attribute search against. - */ - public void setFolderType(String folderType) - { - this.folderType = folderType; - } - - /** - * @return Returns the mimeType. - */ - public String getMimeType() - { - return this.mimeType; - } - /** - * @param mimeType The mimeType to set. - */ - public void setMimeType(String mimeType) - { - this.mimeType = mimeType; - } - - /** - * Add an additional attribute to search against for simple searches - * - * @param qname QName of the attribute to search against - */ - public void addSimpleAttributeQuery(QName qname) - { - this.simpleSearchAdditionalAttrs.add(qname); - } - - /** - * Sets the additional attribute to search against for simple searches. - * - * @param attrs The list of attributes to search against - */ - public void setSimpleSearchAdditionalAttributes(List attrs) - { - if (attrs != null) - { - this.simpleSearchAdditionalAttrs = attrs; - } - } - - /** - * Add an additional attribute to search against - * - * @param qname QName of the attribute to search against - * @param value Value of the attribute to use - */ - public void addAttributeQuery(QName qname, String value) - { - this.queryAttributes.put(qname, value); - } - - public String getAttributeQuery(QName qname) - { - return this.queryAttributes.get(qname); - } - - /** - * Add an additional range attribute to search against - * - * @param qname QName of the attribute to search against - * @param lower Lower value for range - * @param upper Upper value for range - * @param inclusive True for inclusive within the range, false otherwise - */ - public void addRangeQuery(QName qname, String lower, String upper, boolean inclusive) - { - this.rangeAttributes.put(qname, new RangeProperties(qname, lower, upper, inclusive)); - } - - public RangeProperties getRangeProperty(QName qname) - { - return this.rangeAttributes.get(qname); - } - - /** - * Add an additional fixed value attribute to search against - * - * @param qname QName of the attribute to search against - * @param value Fixed value of the attribute to use - */ - public void addFixedValueQuery(QName qname, String value) - { - this.queryFixedValues.put(qname, value); - } - - public String getFixedValueQuery(QName qname) - { - return this.queryFixedValues.get(qname); - } - - /** - * @return Returns if AND is forced between text terms. False (OR terms) is the default. - */ - public boolean getForceAndTerms() - { - return this.forceAndTerms; - } - - /** - * @param forceAndTerms Set true to force AND between text terms. Otherwise OR is the default. - */ - public void setForceAndTerms(boolean forceAndTerms) - { - this.forceAndTerms = forceAndTerms; - } - - /** - * @return this SearchContext as XML - * - * Example: - * - * - * - * CDATA - * int - * XPath - * - * XPath - * - * String - * String - * String - * - * String - * - * - * - * String - * String - * boolean - * - * - * - * String - * - * CDATA - * - * - */ - public String toXML() - { - try - { - NamespaceService ns = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNamespaceService(); - - Document doc = DocumentHelper.createDocument(); - - Element root = doc.addElement(ELEMENT_SEARCH); - - root.addElement(ELEMENT_TEXT).addCDATA(this.text); - root.addElement(ELEMENT_MODE).addText(Integer.toString(this.mode)); - if (this.location != null) - { - root.addElement(ELEMENT_LOCATION).addText(this.location); - } - - Element categories = root.addElement(ELEMENT_CATEGORIES); - for (String path : this.categories) - { - categories.addElement(ELEMENT_CATEGORY).addText(path); - } - - if (this.contentType != null) - { - root.addElement(ELEMENT_CONTENT_TYPE).addText(this.contentType); - } - if (this.folderType != null) - { - root.addElement(ELEMENT_FOLDER_TYPE).addText(this.folderType); - } - if (this.mimeType != null && this.mimeType.length() != 0) - { - root.addElement(ELEMENT_MIMETYPE).addText(this.mimeType); - } - - Element attributes = root.addElement(ELEMENT_ATTRIBUTES); - for (QName attrName : this.queryAttributes.keySet()) - { - attributes.addElement(ELEMENT_ATTRIBUTE) - .addAttribute(ELEMENT_NAME, attrName.toPrefixString(ns)) - .addCDATA(this.queryAttributes.get(attrName)); - } - - Element ranges = root.addElement(ELEMENT_RANGES); - for (QName rangeName : this.rangeAttributes.keySet()) - { - RangeProperties rangeProps = this.rangeAttributes.get(rangeName); - Element range = ranges.addElement(ELEMENT_RANGE); - range.addAttribute(ELEMENT_NAME, rangeName.toPrefixString(ns)); - range.addElement(ELEMENT_LOWER).addText(rangeProps.lower); - range.addElement(ELEMENT_UPPER).addText(rangeProps.upper); - range.addElement(ELEMENT_INCLUSIVE).addText(Boolean.toString(rangeProps.inclusive)); - } - - Element values = root.addElement(ELEMENT_FIXED_VALUES); - for (QName valueName : this.queryFixedValues.keySet()) - { - values.addElement(ELEMENT_VALUE) - .addAttribute(ELEMENT_NAME, valueName.toPrefixString(ns)) - .addCDATA(this.queryFixedValues.get(valueName)); - } - - // outputing the full lucene query may be useful for some situations - Element query = root.addElement(ELEMENT_QUERY); - String queryString = buildQuery(0); - if (queryString != null) - { - query.addCDATA(queryString); - } - - StringWriter out = new StringWriter(1024); - XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint()); - writer.setWriter(out); - writer.write(doc); - - return out.toString(); - } - catch (Throwable err) - { - throw new AlfrescoRuntimeException("Failed to export SearchContext to XML.", err); - } - } - - /** - * Restore a SearchContext from an XML definition - * - * @param xml XML format SearchContext @see #toXML() - */ - public SearchContext fromXML(String xml) - { - try - { - NamespaceService ns = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNamespaceService(); - - // get the root element - SAXReader reader = new SAXReader(); - Document document = reader.read(new StringReader(xml)); - Element rootElement = document.getRootElement(); - Element textElement = rootElement.element(ELEMENT_TEXT); - if (textElement != null) - { - this.text = textElement.getText(); - } - Element modeElement = rootElement.element(ELEMENT_MODE); - if (modeElement != null) - { - this.mode = Integer.parseInt(modeElement.getText()); - } - Element locationElement = rootElement.element(ELEMENT_LOCATION); - if (locationElement != null) - { - this.location = locationElement.getText(); - } - Element categoriesElement = rootElement.element(ELEMENT_CATEGORIES); - if (categoriesElement != null) - { - List categories = new ArrayList(4); - for (Iterator i=categoriesElement.elementIterator(ELEMENT_CATEGORY); i.hasNext(); /**/) - { - Element categoryElement = (Element)i.next(); - categories.add(categoryElement.getText()); - } - this.categories = categories.toArray(this.categories); - } - Element contentTypeElement = rootElement.element(ELEMENT_CONTENT_TYPE); - if (contentTypeElement != null) - { - this.contentType = contentTypeElement.getText(); - } - Element folderTypeElement = rootElement.element(ELEMENT_FOLDER_TYPE); - if (folderTypeElement != null) - { - this.folderType = folderTypeElement.getText(); - } - Element mimetypeElement = rootElement.element(ELEMENT_MIMETYPE); - if (mimetypeElement != null) - { - this.mimeType = mimetypeElement.getText(); - } - Element attributesElement = rootElement.element(ELEMENT_ATTRIBUTES); - if (attributesElement != null) - { - for (Iterator i=attributesElement.elementIterator(ELEMENT_ATTRIBUTE); i.hasNext(); /**/) - { - Element attrElement = (Element)i.next(); - QName qname = QName.createQName(attrElement.attributeValue(ELEMENT_NAME), ns); - addAttributeQuery(qname, attrElement.getText()); - } - } - Element rangesElement = rootElement.element(ELEMENT_RANGES); - if (rangesElement != null) - { - for (Iterator i=rangesElement.elementIterator(ELEMENT_RANGE); i.hasNext(); /**/) - { - Element rangeElement = (Element)i.next(); - Element lowerElement = rangeElement.element(ELEMENT_LOWER); - Element upperElement = rangeElement.element(ELEMENT_UPPER); - Element incElement = rangeElement.element(ELEMENT_INCLUSIVE); - if (lowerElement != null && upperElement != null && incElement != null) - { - QName qname = QName.createQName(rangeElement.attributeValue(ELEMENT_NAME), ns); - addRangeQuery(qname, - lowerElement.getText(), upperElement.getText(), - Boolean.parseBoolean(incElement.getText())); - } - } - } - - Element valuesElement = rootElement.element(ELEMENT_FIXED_VALUES); - if (valuesElement != null) - { - for (Iterator i=valuesElement.elementIterator(ELEMENT_VALUE); i.hasNext(); /**/) - { - Element valueElement = (Element)i.next(); - QName qname = QName.createQName(valueElement.attributeValue(ELEMENT_NAME), ns); - addFixedValueQuery(qname, valueElement.getText()); - } - } - } - catch (Throwable err) - { - throw new AlfrescoRuntimeException("Failed to import SearchContext from XML.", err); - } - return this; - } - - /** - * Simple wrapper class for range query attribute properties - */ - static class RangeProperties implements Serializable - { - private static final long serialVersionUID = 5627339191207625169L; - - QName qname; - String lower; - String upper; - boolean inclusive; - - RangeProperties(QName qname, String lower, String upper, boolean inclusive) - { - this.qname = qname; - this.lower = lower; - this.upper = upper; - this.inclusive = inclusive; - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/search/SearchProperties.java b/war/src/main/java/org/alfresco/web/bean/search/SearchProperties.java deleted file mode 100644 index 0c05aa778b..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/search/SearchProperties.java +++ /dev/null @@ -1,520 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.search; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.model.DataModel; -import javax.faces.model.ListDataModel; -import javax.faces.model.SelectItem; - -import org.alfresco.service.cmr.dictionary.DataTypeDefinition; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.util.ExpiringValueCache; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.config.AdvancedSearchConfigElement; - -public class SearchProperties implements Serializable -{ - private static final long serialVersionUID = 8583342903708013641L; - - private static final String MODE_ALL = "all"; - private static final String LOOKIN_ALL = "all"; - private static final String SAVED_SEARCHES_USER = "user"; - - /** Client Config reference */ - private AdvancedSearchConfigElement searchConfigElement = null; - - /** Progressive panel UI state */ - private Map panels = new HashMap(5, 1.0f); - - /** Saved search properties */ - private String searchName; - private String searchDescription; - - /** custom property names to values */ - private Map customProperties = new HashMap(5, 1.0f); - - /** - * lookup of custom property QName string to DataTypeDefinition for the property - */ - transient private Map customPropertyLookup = null; - - /** content format list restricting searches */ - private List contentFormats; - - /** content format selection */ - private String contentFormat; - - /** content type selection */ - private String contentType; - - /** content types for restricting searches */ - private List contentTypes; - - /** folder type selection */ - private String folderType; - - /** folder types for restricting searches */ - private List folderTypes; - - /** the text to search for */ - private String text = ""; - - /** search mode */ - private String mode = MODE_ALL; - - /** folder lookin mode */ - private String lookin = LOOKIN_ALL; - - /** Space Selector location */ - private NodeRef location = null; - - /** categories to search */ - private List categories = new ArrayList(2); - - /** datamodel for table of categories to search */ - transient private DataModel categoriesDataModel = null; - - /** title attribute to search */ - private String title = null; - - /** description attribute to search */ - private String description = null; - - /** created attribute to search from */ - private Date createdDateFrom = null; - - /** created attribute to search to */ - private Date createdDateTo = null; - - /** modified attribute to search from */ - private Date modifiedDateFrom = null; - - /** modified attribute to search to */ - private Date modifiedDateTo = null; - - /** true to search location children as well as location */ - private boolean locationChildren = true; - - /** author (creator) attribute to search */ - private String author = null; - - private boolean modifiedDateChecked = false; - private boolean createdDateChecked = false; - - /** cached ref to the global saved searches folder */ - private NodeRef globalSearchesRef = null; - - /** cached ref to the current users saved searches folder */ - private NodeRef userSearchesRef = null; - - /** ID to the last selected saved search */ - private String savedSearch = null; - - /** ModeList component value for selecting user/global searches */ - private String savedSearchMode = SAVED_SEARCHES_USER; - - /** name of the saved search to edit */ - private String editSearchName = null; - - /** form field for saving search as user/global */ - private boolean searchSaveGlobal = false; - - /** auto-expiring cache of the list of saved searches */ - private ExpiringValueCache> cachedSavedSearches = new ExpiringValueCache>(); - - - public AdvancedSearchConfigElement getSearchConfigElement() - { - return searchConfigElement; - } - - public void setSearchConfigElement(AdvancedSearchConfigElement searchConfigElement) - { - this.searchConfigElement = searchConfigElement; - } - - public Map getPanels() - { - return panels; - } - - public void setPanels(Map panels) - { - this.panels = panels; - } - - public String getSearchName() - { - return searchName; - } - - public void setSearchName(String searchName) - { - this.searchName = searchName; - } - - public String getSearchDescription() - { - return searchDescription; - } - - public void setSearchDescription(String searchDescription) - { - this.searchDescription = searchDescription; - } - - public Map getCustomProperties() - { - return customProperties; - } - - public void setCustomProperties(Map customProperties) - { - this.customProperties = customProperties; - } - - public Map getCustomPropertyLookup() - { - return customPropertyLookup; - } - - public void setCustomPropertyLookup(Map customPropertyLookup) - { - this.customPropertyLookup = customPropertyLookup; - } - - public List getContentFormats() - { - return contentFormats; - } - - public void setContentFormats(List contentFormats) - { - this.contentFormats = contentFormats; - } - - public String getContentFormat() - { - return contentFormat; - } - - public void setContentFormat(String contentFormat) - { - this.contentFormat = contentFormat; - } - - public String getContentType() - { - return contentType; - } - - public void setContentType(String contentType) - { - this.contentType = contentType; - } - - public List getContentTypes() - { - return contentTypes; - } - - public void setContentTypes(List contentTypes) - { - this.contentTypes = contentTypes; - } - - public String getFolderType() - { - return folderType; - } - - public void setFolderType(String folderType) - { - this.folderType = folderType; - } - - public List getFolderTypes() - { - return folderTypes; - } - - public void setFolderTypes(List folderTypes) - { - this.folderTypes = folderTypes; - } - - public String getText() - { - return text; - } - - public void setText(String text) - { - this.text = text; - } - - public String getMode() - { - return mode; - } - - public void setMode(String mode) - { - this.mode = mode; - } - - public String getLookin() - { - return lookin; - } - - public void setLookin(String lookin) - { - this.lookin = lookin; - } - - public NodeRef getLocation() - { - return location; - } - - public void setLocation(NodeRef location) - { - this.location = location; - } - - public List getCategories() - { - return categories; - } - - public void setCategories(List categories) - { - this.categories = categories; - } - - public DataModel getCategoriesDataModel() - { - if (categoriesDataModel == null) - { - categoriesDataModel = new ListDataModel(); - } - - return categoriesDataModel; - } - - public void setCategoriesDataModel(DataModel categoriesDataModel) - { - this.categoriesDataModel = categoriesDataModel; - } - - public String getTitle() - { - return title; - } - - public void setTitle(String title) - { - this.title = title; - } - - public String getDescription() - { - return description; - } - - public void setDescription(String description) - { - this.description = description; - } - - public Date getCreatedDateFrom() - { - return createdDateFrom; - } - - public void setCreatedDateFrom(Date createdDateFrom) - { - this.createdDateFrom = createdDateFrom; - } - - public Date getCreatedDateTo() - { - return createdDateTo; - } - - public void setCreatedDateTo(Date createdDateTo) - { - this.createdDateTo = createdDateTo; - } - - public Date getModifiedDateFrom() - { - return modifiedDateFrom; - } - - public void setModifiedDateFrom(Date modifiedDateFrom) - { - this.modifiedDateFrom = modifiedDateFrom; - } - - public Date getModifiedDateTo() - { - return modifiedDateTo; - } - - public void setModifiedDateTo(Date modifiedDateTo) - { - this.modifiedDateTo = modifiedDateTo; - } - - public boolean isLocationChildren() - { - return locationChildren; - } - - public void setLocationChildren(boolean locationChildren) - { - this.locationChildren = locationChildren; - } - - public String getAuthor() - { - return author; - } - - public void setAuthor(String author) - { - this.author = author; - } - - public boolean isModifiedDateChecked() - { - return modifiedDateChecked; - } - - public void setModifiedDateChecked(boolean modifiedDateChecked) - { - this.modifiedDateChecked = modifiedDateChecked; - } - - public boolean isCreatedDateChecked() - { - return createdDateChecked; - } - - public void setCreatedDateChecked(boolean createdDateChecked) - { - this.createdDateChecked = createdDateChecked; - } - - public NodeRef getGlobalSearchesRef() - { - return globalSearchesRef; - } - - public void setGlobalSearchesRef(NodeRef globalSearchesRef) - { - this.globalSearchesRef = globalSearchesRef; - } - - public NodeRef getUserSearchesRef() - { - return userSearchesRef; - } - - public void setUserSearchesRef(NodeRef userSearchesRef) - { - this.userSearchesRef = userSearchesRef; - } - - public String getSavedSearch() - { - return savedSearch; - } - - public void setSavedSearch(String savedSearch) - { - this.savedSearch = savedSearch; - } - - public String getSavedSearchMode() - { - return savedSearchMode; - } - - public void setSavedSearchMode(String savedSearchMode) - { - this.savedSearchMode = savedSearchMode; - } - - public String getEditSearchName() - { - return editSearchName; - } - - public void setEditSearchName(String editSearchName) - { - this.editSearchName = editSearchName; - } - - public boolean isSearchSaveGlobal() - { - return searchSaveGlobal; - } - - public void setSearchSaveGlobal(boolean searchSaveGlobal) - { - this.searchSaveGlobal = searchSaveGlobal; - } - - public ExpiringValueCache> getCachedSavedSearches() - { - return cachedSavedSearches; - } - - public void setCachedSavedSearches(ExpiringValueCache> cachedSavedSearches) - { - this.cachedSavedSearches = cachedSavedSearches; - } - - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException - { - in.defaultReadObject(); - - categoriesDataModel = new ListDataModel(); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/spaces/ApplyDocTemplateDialog.java b/war/src/main/java/org/alfresco/web/bean/spaces/ApplyDocTemplateDialog.java deleted file mode 100644 index f2f017a55d..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/spaces/ApplyDocTemplateDialog.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.spaces; - -import java.text.MessageFormat; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.TemplateSupportBean; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; - -public class ApplyDocTemplateDialog extends BaseDialogBean -{ - private static final long serialVersionUID = -9098279672434597354L; - - private static final String DIALOG_CLOSE = "dialog:close"; - private static final String MSG_APPLY_TEMPLATE = "apply_template"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - protected String template; - - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - if (this.template != null && this.template.equals(TemplateSupportBean.NO_SELECTION) == false) - { - try - { - // apply the templatable aspect if required - if (getNode().hasAspect(ContentModel.ASPECT_TEMPLATABLE) == false) - { - this.getNodeService().addAspect(getNode().getNodeRef(), ContentModel.ASPECT_TEMPLATABLE, null); - } - - // get the selected template from the Template Picker - NodeRef templateRef = new NodeRef(Repository.getStoreRef(), this.template); - - // set the template NodeRef into the templatable aspect property - this.getNodeService().setProperty(getNode().getNodeRef(), ContentModel.PROP_TEMPLATE, templateRef); - - // reset node details for next refresh of details page - getNode().reset(); - } - catch (Exception e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), e.getMessage()), e); - ReportedException.throwIfNecessary(e); - } - } - return DIALOG_CLOSE; - } - - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_APPLY_TEMPLATE) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) + getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - public String getTemplate() - { - // return current template if it exists - NodeRef ref = (NodeRef) getNode().getProperties().get(ContentModel.PROP_TEMPLATE); - return ref != null ? ref.getId() : this.template; - } - - public void setTemplate(String template) - { - this.template = template; - } - - public Node getNode() - { - return this.browseBean.getDocument(); - } - - public String getName() - { - return getNode().getName(); - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/bean/spaces/ApplyRssTemplateDialog.java b/war/src/main/java/org/alfresco/web/bean/spaces/ApplyRssTemplateDialog.java deleted file mode 100644 index d197d5c381..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/spaces/ApplyRssTemplateDialog.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.spaces; - -import java.text.MessageFormat; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.TemplateSupportBean; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; - -public class ApplyRssTemplateDialog extends BaseDialogBean -{ - private static final long serialVersionUID = 9207265799149337182L; - - private static final String DIALOG_CLOSE = "dialog:close"; - private static final String MSG_APPLY_RSS_FEED = "apply_rss_feed"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - private String rssTemplate; - - - public void setRSSTemplate(String rssTemplate) - { - this.rssTemplate = rssTemplate; - } - - /** - * @return Returns the current RSS Template ID. - */ - public String getRSSTemplate() - { - // return current template if it exists - NodeRef ref = (NodeRef) getNode().getProperties().get(ApplicationModel.PROP_FEEDTEMPLATE); - return ref != null ? ref.getId() : this.rssTemplate; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - applyRSSTemplate(null); - return DIALOG_CLOSE; - } - - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_APPLY_RSS_FEED) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) + getNode().getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - public void applyRSSTemplate(ActionEvent event) - { - if (this.rssTemplate != null && this.rssTemplate.equals(TemplateSupportBean.NO_SELECTION) == false) - { - try - { - // apply the feedsource aspect if required - if (getNode().hasAspect(ApplicationModel.ASPECT_FEEDSOURCE) == false) - { - this.getNodeService().addAspect(getNode().getNodeRef(), ApplicationModel.ASPECT_FEEDSOURCE, null); - } - - // get the selected template Id from the Template Picker - NodeRef templateRef = new NodeRef(Repository.getStoreRef(), this.rssTemplate); - - // set the template NodeRef into the templatable aspect property - this.getNodeService().setProperty(getNode().getNodeRef(), ApplicationModel.PROP_FEEDTEMPLATE, templateRef); - - // reset node details for next refresh of details page - getNode().reset(); - } - catch (Exception e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), e.getMessage()), e); - ReportedException.throwIfNecessary(e); - } - } - } - - /** - * Returns the Node this bean is currently representing - * - * @return The Node - */ - public Node getNode() - { - return this.browseBean.getActionSpace(); - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/bean/spaces/ApplySpaceTemplateDialog.java b/war/src/main/java/org/alfresco/web/bean/spaces/ApplySpaceTemplateDialog.java deleted file mode 100644 index 29a6bed661..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/spaces/ApplySpaceTemplateDialog.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.spaces; - -import java.text.MessageFormat; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.TemplateSupportBean; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; - -public class ApplySpaceTemplateDialog extends BaseDialogBean -{ - private static final long serialVersionUID = -3019234033026890265L; - - private static final String DIALOG_CLOSE = "dialog:close"; - private static final String MSG_APPLY_TEMPLATE = "apply_template"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - protected String template; - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - applyTemplate(null); - return DIALOG_CLOSE; - } - - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_APPLY_TEMPLATE) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) + getNode().getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - public void applyTemplate(ActionEvent event) - { - if (this.template != null && this.template.equals(TemplateSupportBean.NO_SELECTION) == false) - { - try - { - // apply the templatable aspect if required - if (getNode().hasAspect(ContentModel.ASPECT_TEMPLATABLE) == false) - { - this.getNodeService().addAspect(getNode().getNodeRef(), ContentModel.ASPECT_TEMPLATABLE, null); - } - - // get the selected template from the Template Picker - NodeRef templateRef = new NodeRef(Repository.getStoreRef(), this.template); - - // set the template NodeRef into the templatable aspect property - this.getNodeService().setProperty(getNode().getNodeRef(), ContentModel.PROP_TEMPLATE, templateRef); - - // reset node details for next refresh of details page - getNode().reset(); - } - catch (Exception e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), e.getMessage()), e); - ReportedException.throwIfNecessary(e); - } - } - } - - public Node getNode() - { - return this.browseBean.getActionSpace(); - } - - public String getTemplate() - { - // return current template if it exists - NodeRef ref = (NodeRef) getNode().getProperties().get(ContentModel.PROP_TEMPLATE); - return ref != null ? ref.getId() : this.template; - } - - public void setTemplate(String template) - { - this.template = template; - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/bean/spaces/CreateSpaceDialog.java b/war/src/main/java/org/alfresco/web/bean/spaces/CreateSpaceDialog.java deleted file mode 100644 index 7ab51943d7..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/spaces/CreateSpaceDialog.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.spaces; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.app.Application; - -/** - * Dialog bean to create a space. - * Uses the CreateSpaceWizard and just overrides the finish button label - * and the default outcomes. - * - * @author gavinc - */ -public class CreateSpaceDialog extends CreateSpaceWizard -{ - private static final long serialVersionUID = 4659583264588102372L; - // ------------------------------------------------------------------------------ - // Wizard implementation - - - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "create_space"); - } - - @Override - protected String getDefaultCancelOutcome() - { - return AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME; - } - - @Override - protected String getDefaultFinishOutcome() - { - return AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/spaces/CreateSpaceWizard.java b/war/src/main/java/org/alfresco/web/bean/spaces/CreateSpaceWizard.java deleted file mode 100644 index 896ec4a840..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/spaces/CreateSpaceWizard.java +++ /dev/null @@ -1,769 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.spaces; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.ResourceBundle; - -import javax.faces.context.FacesContext; -import javax.faces.model.SelectItem; - -import org.springframework.extensions.config.Config; -import org.springframework.extensions.config.ConfigElement; -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.dictionary.TypeDefinition; -import org.alfresco.service.cmr.model.FileExistsException; -import org.alfresco.service.cmr.model.FileInfo; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.DynamicNamespacePrefixResolver; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.wizard.BaseWizardBean; -import org.alfresco.web.data.IDataContainer; -import org.alfresco.web.data.QuickSort; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIListItem; -import org.alfresco.web.ui.common.component.description.UIDescription; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean responsible for the create space wizard - * - * @author gavinc - */ -public class CreateSpaceWizard extends BaseWizardBean -{ - private static final long serialVersionUID = 2917623558917193097L; - - public static final String DEFAULT_SPACE_ICON_NAME = "space-icon-default"; - public static final String DEFAULT_SPACE_ICON_PATH = ""; - public static final String DEFAULT_SPACE_TYPE_ICON_PATH = "/images/icons/space.gif"; - - private static Log logger = LogFactory.getLog(CreateSpaceWizard.class); - - protected static final String CREATEFROM_TEMPLATE = "template"; - protected static final String CREATEFROM_EXISTING = "existing"; - protected static final String CREATEFROM_SCRATCH = "scratch"; - - protected String spaceType; - protected String icon; - protected String createFrom; - protected NodeRef existingSpaceId; - protected String templateSpaceId; - protected String copyPolicy; - protected String name; - protected String title; - protected String description; - protected String templateName; - protected boolean saveAsTemplate; - protected List templates; - protected List folderTypes; - protected List folderTypeDescriptions; - - // the NodeRef of the node created during finish - protected NodeRef createdNode; - - // ------------------------------------------------------------------------------ - // Wizard implementation - - /** - * Initialises the wizard - */ - public void init(Map parameters) - { - super.init(parameters); - - // clear the cached query results - if (this.templates != null) - { - this.templates.clear(); - this.templates = null; - } - - // reset all variables - this.createFrom = CREATEFROM_SCRATCH; - this.spaceType = ContentModel.TYPE_FOLDER.toString(); - this.icon = null; - this.copyPolicy = "contents"; - this.existingSpaceId = null; - this.templateSpaceId = null; - this.name = null; - this.title = null; - this.description = null; - this.templateName = null; - this.saveAsTemplate = false; - } - - public String next() - { - // if the user has chosen to create the space from an existing - // space or from a template we need to find it's type to show - // the current set of icons. - if (this.createFrom.equals(CREATEFROM_EXISTING) && this.existingSpaceId != null) - { - this.spaceType = this.getNodeService().getType(this.existingSpaceId).toString(); - } - else if (this.createFrom.equals(CREATEFROM_TEMPLATE) && this.templateSpaceId != null && - !this.templateSpaceId.equals("none")) - { - NodeRef templateNode = new NodeRef(Repository.getStoreRef(), this.templateSpaceId); - this.spaceType = this.getNodeService().getType(templateNode).toString(); - } - - return null; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - String newSpaceId = null; - - if (this.createFrom.equals(CREATEFROM_SCRATCH)) - { - // create the space (just create a folder for now) - NodeRef parentNodeRef; - String nodeId = this.navigator.getCurrentNodeId(); - if (nodeId == null) - { - parentNodeRef = this.getNodeService().getRootNode(Repository.getStoreRef()); - } - else - { - parentNodeRef = new NodeRef(Repository.getStoreRef(), nodeId); - } - - FileInfo fileInfo = getFileFolderService().create( - parentNodeRef, - this.name, - Repository.resolveToQName(this.spaceType)); - NodeRef nodeRef = fileInfo.getNodeRef(); - newSpaceId = nodeRef.getId(); - - if (logger.isDebugEnabled()) - logger.debug("Created folder node with name: " + this.name); - - // apply the uifacets aspect - icon, title and description props - Map uiFacetsProps = new HashMap(5); - uiFacetsProps.put(ApplicationModel.PROP_ICON, this.icon); - uiFacetsProps.put(ContentModel.PROP_TITLE, this.title); - uiFacetsProps.put(ContentModel.PROP_DESCRIPTION, this.description); - this.getNodeService().addAspect(nodeRef, ApplicationModel.ASPECT_UIFACETS, uiFacetsProps); - - if (logger.isDebugEnabled()) - logger.debug("Added uifacets aspect with properties: " + uiFacetsProps); - - // remember the created node - this.createdNode = nodeRef; - } - else if (this.createFrom.equals(CREATEFROM_EXISTING)) - { - // copy the selected space and update the name, description and icon - NodeRef sourceNode = this.existingSpaceId; - NodeRef parentSpace = new NodeRef(Repository.getStoreRef(), this.navigator.getCurrentNodeId()); - - // copy from existing - NodeRef copiedNode = this.getFileFolderService().copy(sourceNode, parentSpace, this.name).getNodeRef(); - - // also need to set the new title, description and icon properties - this.getNodeService().setProperty(copiedNode, ContentModel.PROP_TITLE, this.title); - this.getNodeService().setProperty(copiedNode, ContentModel.PROP_DESCRIPTION, this.description); - this.getNodeService().setProperty(copiedNode, ApplicationModel.PROP_ICON, this.icon); - - newSpaceId = copiedNode.getId(); - - if (logger.isDebugEnabled()) - logger.debug("Copied space with id of " + sourceNode.getId() + " to " + this.name); - - // remember the created node - this.createdNode = copiedNode; - } - else if (this.createFrom.equals(CREATEFROM_TEMPLATE)) - { - // copy the selected space and update the name, description and icon - NodeRef sourceNode = new NodeRef(Repository.getStoreRef(), this.templateSpaceId); - NodeRef parentSpace = new NodeRef(Repository.getStoreRef(), this.navigator.getCurrentNodeId()); - // copy from the template - NodeRef copiedNode = this.getFileFolderService().copy(sourceNode, parentSpace, this.name).getNodeRef(); - // also need to set the new title, description and icon properties - this.getNodeService().setProperty(copiedNode, ContentModel.PROP_TITLE, this.title); - this.getNodeService().setProperty(copiedNode, ContentModel.PROP_DESCRIPTION, this.description); - this.getNodeService().setProperty(copiedNode, ApplicationModel.PROP_ICON, this.icon); - - newSpaceId = copiedNode.getId(); - - if (logger.isDebugEnabled()) - logger.debug("Copied template space with id of " + sourceNode.getId() + " to " + this.name); - - // remember the created node - this.createdNode = copiedNode; - } - - // if the user selected to save the space as a template space copy the new - // space to the templates folder - if (this.saveAsTemplate) - { - // get hold of the Templates node - DynamicNamespacePrefixResolver namespacePrefixResolver = new DynamicNamespacePrefixResolver(null); - namespacePrefixResolver.registerNamespace(NamespaceService.APP_MODEL_PREFIX, NamespaceService.APP_MODEL_1_0_URI); - - String xpath = Application.getRootPath(FacesContext.getCurrentInstance()) + "/" + - Application.getGlossaryFolderName(FacesContext.getCurrentInstance()) + "/" + - Application.getSpaceTemplatesFolderName(FacesContext.getCurrentInstance()); - - NodeRef rootNodeRef = this.getNodeService().getRootNode(Repository.getStoreRef()); - List templateNodeList = this.getSearchService().selectNodes( - rootNodeRef, - xpath, null, namespacePrefixResolver, false); - if (templateNodeList.size() == 1) - { - // get the first item in the list as we from test above there is only one! - NodeRef templateNode = templateNodeList.get(0); - NodeRef sourceNode = new NodeRef(Repository.getStoreRef(), newSpaceId); - // copy this to the template location - getFileFolderService().copy(sourceNode, templateNode, this.templateName); - } - } - - return outcome; - } - - // ------------------------------------------------------------------------------ - // Bean Getters and Setters - - /** - * @return Returns the copyPolicy. - */ - public String getCopyPolicy() - { - return copyPolicy; - } - - /** - * @param copyPolicy The copyPolicy to set. - */ - public void setCopyPolicy(String copyPolicy) - { - this.copyPolicy = copyPolicy; - } - - /** - * @return Returns the createFrom. - */ - public String getCreateFrom() - { - return createFrom; - } - - /** - * @param createFrom The createFrom to set. - */ - public void setCreateFrom(String createFrom) - { - this.createFrom = createFrom; - } - - /** - * @return Returns the description. - */ - public String getDescription() - { - return description; - } - - /** - * @param description The description to set. - */ - public void setDescription(String description) - { - this.description = description; - } - - /** - * @return Returns the existingSpaceId. - */ - public NodeRef getExistingSpaceId() - { - return existingSpaceId; - } - - /** - * @param existingSpaceId The existingSpaceId to set. - */ - public void setExistingSpaceId(NodeRef existingSpaceId) - { - this.existingSpaceId = existingSpaceId; - } - - /** - * @return Returns the icon. - */ - public String getIcon() - { - return icon; - } - - /** - * @param icon The icon to set. - */ - public void setIcon(String icon) - { - this.icon = icon; - } - - /** - * @return Returns the name. - */ - public String getName() - { - return name; - } - - /** - * @param name The name to set. - */ - public void setName(String name) - { - this.name = name.trim(); - } - - /** - * @return Returns the title. - */ - public String getTitle() - { - return title; - } - - /** - * @param title The title to set. - */ - public void setTitle(String title) - { - this.title = title; - } - - /** - * @return Returns the saveAsTemplate. - */ - public boolean isSaveAsTemplate() - { - return saveAsTemplate; - } - - /** - * @param saveAsTemplate The saveAsTemplate to set. - */ - public void setSaveAsTemplate(boolean saveAsTemplate) - { - this.saveAsTemplate = saveAsTemplate; - } - - /** - * @return Returns the spaceType. - */ - public String getSpaceType() - { - return spaceType; - } - - /** - * @param spaceType The spaceType to set. - */ - public void setSpaceType(String spaceType) - { - this.spaceType = spaceType; - } - - /** - * @return Returns the templateName. - */ - public String getTemplateName() - { - return templateName; - } - - /** - * @param templateName The templateName to set. - */ - public void setTemplateName(String templateName) - { - this.templateName = templateName; - } - - /** - * @return Returns the templateSpaceId. - */ - public String getTemplateSpaceId() - { - return templateSpaceId; - } - - /** - * @param templateSpaceId The templateSpaceId to set. - */ - public void setTemplateSpaceId(String templateSpaceId) - { - this.templateSpaceId = templateSpaceId; - } - - /** - * @return Returns the summary data for the wizard. - */ - public String getSummary() - { - String summaryCreateType = null; - ResourceBundle bundle = Application.getBundle(FacesContext.getCurrentInstance()); - - if (this.createFrom.equals(CREATEFROM_SCRATCH)) - { - summaryCreateType = bundle.getString(CREATEFROM_SCRATCH); - } - else if (this.createFrom.equals(CREATEFROM_EXISTING)) - { - summaryCreateType = bundle.getString("an_existing_space"); - } - else if (this.createFrom.equals(CREATEFROM_TEMPLATE)) - { - summaryCreateType = bundle.getString("a_template"); - } - -// String summarySaveAsTemplate = this.saveAsTemplate ? bundle.getString("yes") : bundle.getString("no"); -// bundle.getString("save_as_template"), bundle.getString("template_name")}, -// summarySaveAsTemplate, this.templateName - - String spaceTypeLabel = null; - for (UIListItem item : this.getFolderTypes()) - { - if (item.getValue().equals(this.spaceType)) - { - spaceTypeLabel = item.getLabel(); - break; - } - } - - return buildSummary( - new String[] {bundle.getString("space_type"), bundle.getString("name"), - bundle.getString("description"), bundle.getString("creating_from")}, - new String[] {spaceTypeLabel, Utils.encode(this.name), Utils.encode(this.description), summaryCreateType}); - } - - /** - * @return Returns a list of template spaces currently in the system - */ - public List getTemplateSpaces() - { - if (this.templates == null) - { - this.templates = new ArrayList(); - - FacesContext context = FacesContext.getCurrentInstance(); - String xpath = Application.getRootPath(context) + "/" + Application.getGlossaryFolderName(context) + - "/" + Application.getSpaceTemplatesFolderName(context) + "/*"; - NodeRef rootNodeRef = this.getNodeService().getRootNode(Repository.getStoreRef()); - List results = this.getSearchService().selectNodes(rootNodeRef, xpath, null, this.getNamespaceService(), false); - - if (results.size() != 0) - { - // show templates of the type relating to the space we are creating - QName spaceType = QName.createQName(this.spaceType); - for (NodeRef assocRef : results) - { - Node childNode = new Node(assocRef); - if (this.getDictionaryService().isSubClass(childNode.getType(), spaceType)) - { - this.templates.add(new SelectItem(childNode.getId(), childNode.getName())); - } - } - - // make sure the list is sorted by the label - QuickSort sorter = new QuickSort(this.templates, "label", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - } - - // add an entry (at the start) to instruct the user to select a template - this.templates.add(0, new SelectItem("none", Application.getMessage(FacesContext.getCurrentInstance(), "select_a_template"))); - } - - return this.templates; - } - - /** - * Returns a list of UIListItem objects representing the folder types - * and also constructs the list of descriptions for each type - * - * @return List of UIListItem components - */ - @SuppressWarnings("unchecked") - public List getFolderTypes() - { - if ((this.folderTypes == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - FacesContext context = FacesContext.getCurrentInstance(); - this.folderTypes = new ArrayList(2); - this.folderTypeDescriptions = new ArrayList(2); - - // add the well known 'container space' type to start with - UIListItem defaultItem = new UIListItem(); - String defaultLabel = Application.getMessage(context, "container"); - defaultItem.setValue(ContentModel.TYPE_FOLDER.toString()); - defaultItem.setLabel(defaultLabel); - defaultItem.setTooltip(defaultLabel); - defaultItem.setImage(DEFAULT_SPACE_TYPE_ICON_PATH); - this.folderTypes.add(defaultItem); - - UIDescription defaultDesc = new UIDescription(); - defaultDesc.setControlValue(ContentModel.TYPE_FOLDER.toString()); - defaultDesc.setText(Application.getMessage(context, "container_desc")); - this.folderTypeDescriptions.add(defaultDesc); - - // add any configured content sub-types to the list - Config wizardCfg = Application.getConfigService(FacesContext.getCurrentInstance()). - getConfig("Space Wizards"); - if (wizardCfg != null) - { - ConfigElement typesCfg = wizardCfg.getConfigElement("folder-types"); - if (typesCfg != null) - { - for (ConfigElement child : typesCfg.getChildren()) - { - QName idQName = Repository.resolveToQName(child.getAttribute("name")); - if (idQName != null) - { - TypeDefinition typeDef = this.getDictionaryService().getType(idQName); - - if (typeDef != null) - { - if (this.getDictionaryService().isSubClass(typeDef.getName(), ContentModel.TYPE_FOLDER)) - { - // try and get the label from config - String label = Utils.getDisplayLabel(context, child); - - // if there wasn't a client based label try and get it from the dictionary - if (label == null) - { - label = typeDef.getTitle(this.getDictionaryService()); - } - - // finally use the localname if we still haven't found a label - if (label == null) - { - label = idQName.getLocalName(); - } - - // resolve a description string for the type - String description = Utils.getDescription(context, child); - - // if we don't have a local description just use the label - if (description == null) - { - description = label; - } - - // extract the icon to use from the config - String icon = child.getAttribute("icon"); - if (icon == null || icon.length() == 0) - { - icon = DEFAULT_SPACE_TYPE_ICON_PATH; - } - - UIListItem item = new UIListItem(); - item.setValue(idQName.toString()); - item.setLabel(label); - item.setTooltip(label); - item.setImage(icon); - this.folderTypes.add(item); - - UIDescription desc = new UIDescription(); - desc.setControlValue(idQName.toString()); - desc.setText(description); - this.folderTypeDescriptions.add(desc); - } - else - { - logger.warn("Failed to add '" + child.getAttribute("name") + - "' to the list of folder types as the type is not a subtype of cm:folder"); - } - } - else - { - logger.warn("Failed to add '" + child.getAttribute("name") + - "' to the list of folder types as the type is not recognised"); - } - } - else - { - logger.warn("Failed to add '" + child.getAttribute("name") + - "' to the list of folder types as the prefix can not be resolved"); - } - } - } - else - { - logger.warn("Could not find 'folder-types' configuration element"); - } - } - else - { - logger.warn("Could not find 'Space Wizards' configuration section"); - } - - } - - return this.folderTypes; - } - - /** - * Returns a list of UIDescription objects for the folder types - * - * @return A list of UIDescription objects - */ - public List getFolderTypeDescriptions() - { - if ((this.folderTypeDescriptions == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - // call the getFolderType method to construct the list - getFolderTypes(); - } - - return this.folderTypeDescriptions; - } - - /** - * Returns a list of icons to allow the user to select from. - * The list can change according to the type of space being created. - * - * @return A list of icons - */ - @SuppressWarnings("unchecked") - public List getIcons() - { - // NOTE: we can't cache this list as it depends on the space type - // which the user can change during the advanced space wizard - - List icons = null; - List iconNames = new ArrayList(8); - - QName type = QName.createQName(this.spaceType); - String typePrefixForm = type.toPrefixString(this.getNamespaceService()); - - Config config = Application.getConfigService(FacesContext.getCurrentInstance()). - getConfig(typePrefixForm + " icons"); - if (config != null) - { - ConfigElement iconsCfg = config.getConfigElement("icons"); - if (iconsCfg != null) - { - boolean first = true; - for (ConfigElement icon : iconsCfg.getChildren()) - { - String iconName = icon.getAttribute("name"); - String iconPath = icon.getAttribute("path"); - - if (iconName != null && iconPath != null) - { - if (first) - { - // if this is the first icon create the list and make - // the first icon in the list the default - - icons = new ArrayList(iconsCfg.getChildCount()); - if (this.icon == null) - { - // set the default if it is not already - this.icon = iconName; - } - first = false; - } - - UIListItem item = new UIListItem(); - item.setValue(iconName); - item.setImage(iconPath); - icons.add(item); - iconNames.add(iconName); - } - } - } - } - - // if we didn't find any icons display one default choice - if (icons == null) - { - icons = new ArrayList(1); - this.icon = DEFAULT_SPACE_ICON_NAME; - - UIListItem item = new UIListItem(); - item.setValue(DEFAULT_SPACE_ICON_NAME); - item.setImage("/images/icons/space-icon-default.gif"); - icons.add(item); - iconNames.add(DEFAULT_SPACE_ICON_NAME); - } - - // make sure the current value for the icon is valid for the - // current list of icons about to be displayed - if (iconNames.contains(this.icon) == false) - { - this.icon = iconNames.get(0); - } - - return icons; - } - - // ------------------------------------------------------------------------------ - // Helper methods - - /** - * Formats the error message to display if an error occurs during finish processing - * - * @param exception The exception - * @return The formatted message - */ - @Override - protected String formatErrorMessage(Throwable exception) - { - if (exception instanceof FileExistsException) - { - return MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_EXISTS), - ((FileExistsException)exception).getName()); - } - else - { - return MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), "error_space"), - exception.getMessage()); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/spaces/DeleteSpaceAssociationDialog.java b/war/src/main/java/org/alfresco/web/bean/spaces/DeleteSpaceAssociationDialog.java deleted file mode 100644 index 058a654b13..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/spaces/DeleteSpaceAssociationDialog.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.spaces; - -import java.text.MessageFormat; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean implementation for the "Delete Space" dialog - * - * @author gavinc - */ -public class DeleteSpaceAssociationDialog extends DeleteSpaceDialog -{ - private static final Log logger = LogFactory.getLog(DeleteSpaceAssociationDialog.class); - - // ------------------------------------------------------------------------------ - // Dialog implementation - - @Override - protected String finishImpl(FacesContext context, String outcome) - throws Exception - { - // get the space to delete - Node node = this.browseBean.getActionSpace(); - if (node != null) - { - if (logger.isDebugEnabled()) - logger.debug("Trying to delete space association: " + node.getId()); - - NodeRef parentRef = this.navigator.getCurrentNode().getNodeRef(); - QName qname = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, - QName.createValidLocalName(node.getName())); - ChildAssociationRef childAssocRef = new ChildAssociationRef(ContentModel.ASSOC_CONTAINS, - parentRef, qname, node.getNodeRef()); - - // remove the child association - this.getNodeService().removeChildAssociation(childAssocRef); - } - else - { - logger.warn("WARNING: delete called without a current Space!"); - } - - return outcome; - } - - // ------------------------------------------------------------------------------ - // Bean Getters and Setters - - /** - * Returns the confirmation to display to the user before deleting the content. - * - * @return The formatted message to display - */ - public String getConfirmMessage() - { - Node node = this.browseBean.getActionSpace(); - if (node != null) - { - String spaceConfirmMsg = Application.getMessage(FacesContext.getCurrentInstance(), - "delete_space_assoc_confirm"); - return MessageFormat.format(spaceConfirmMsg, new Object[] {node.getName()}); - } - else - { - return Application.getMessage(FacesContext.getCurrentInstance(), - "delete_node_not_found"); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/spaces/DeleteSpaceDialog.java b/war/src/main/java/org/alfresco/web/bean/spaces/DeleteSpaceDialog.java deleted file mode 100644 index 9eeb142c05..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/spaces/DeleteSpaceDialog.java +++ /dev/null @@ -1,345 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.spaces; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.dictionary.TypeDefinition; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.QName; -import org.alfresco.service.namespace.RegexQNamePattern; -import org.alfresco.service.transaction.TransactionService; -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.content.DeleteContentDialog; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean implementation for the "Delete Space" dialog - * - * @author gavinc - */ -public class DeleteSpaceDialog extends BaseDialogBean -{ - private static final long serialVersionUID = 5960844637376808571L; - - private static final Log logger = LogFactory.getLog(DeleteContentDialog.class); - - private static final String DELETE_ALL = "all"; - private static final String DELETE_FILES = "files"; - private static final String DELETE_FOLDERS = "folders"; - private static final String DELETE_CONTENTS = "contents"; - - private String deleteMode = DELETE_ALL; - private boolean executeRules = true; - private boolean archiveNodes = true; - - protected boolean hasMultipleParents = false; - - - // ------------------------------------------------------------------------------ - // Dialog implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - this.hasMultipleParents = false; - - String strHasMultipleParents = this.parameters.get("hasMultipleParents"); - if (strHasMultipleParents != null && "true".equals(strHasMultipleParents)) - { - this.hasMultipleParents = true; - } - } - - @Override - protected String finishImpl(FacesContext context, String outcome) - throws Exception - { - final boolean isAdmin = this.navigator.getCurrentUser().isAdmin(); - // get the space to delete - Node node = this.browseBean.getActionSpace(); - if (node != null) - { - // force cache of name property so we can use it after the delete - node.getName(); - - if (logger.isDebugEnabled()) - logger.debug("Trying to delete space: " + node.getId() + " using delete mode: " + this.deleteMode); - - try - { - if (isAdmin && !this.executeRules) - { - Repository.getServiceRegistry(context).getRuleService().disableRules(); - } - if (DELETE_ALL.equals(this.deleteMode)) - { - NodeRef nodeRef = node.getNodeRef(); - // Check the node still exists - if (this.getNodeService().exists(nodeRef)) - { - if (isAdmin && !this.archiveNodes) - { - this.getNodeService().addAspect(node.getNodeRef(), ContentModel.ASPECT_TEMPORARY, null); - } - - // ensure the node still exists before deleting - if (this.getNodeService().exists(node.getNodeRef())) - { - this.getNodeService().deleteNode(node.getNodeRef()); - } - } - } - else - { - List childRefs = this.getNodeService().getChildAssocs(node.getNodeRef(), - ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL); - List deleteRefs = new ArrayList(childRefs.size()); - for (ChildAssociationRef ref : childRefs) - { - NodeRef nodeRef = ref.getChildRef(); - - if (this.getNodeService().exists(nodeRef)) - { - if (DELETE_CONTENTS.equals(this.deleteMode)) - { - deleteRefs.add(nodeRef); - } - else - { - // find it's type so we can see if it's a node we are interested in - QName type = this.getNodeService().getType(nodeRef); - - // make sure the type is defined in the data dictionary - TypeDefinition typeDef = this.getDictionaryService().getType(type); - - if (typeDef != null) - { - if (DELETE_FOLDERS.equals(this.deleteMode)) - { - // look for folder type - if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_FOLDER) == true && - this.getDictionaryService().isSubClass(type, ContentModel.TYPE_SYSTEM_FOLDER) == false) - { - deleteRefs.add(nodeRef); - } - } - else if (DELETE_FILES.equals(this.deleteMode)) - { - // look for content file type - if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_CONTENT)) - { - deleteRefs.add(nodeRef); - } - } - } - } - } - } - - // delete the list of refs - TransactionService txService = Repository.getServiceRegistry(context).getTransactionService(); - for (NodeRef nodeRef : deleteRefs) - { - UserTransaction tx = null; - - try - { - tx = txService.getNonPropagatingUserTransaction(); - tx.begin(); - - if (isAdmin && !this.archiveNodes) - { - this.getNodeService().addAspect(nodeRef, ContentModel.ASPECT_TEMPORARY, null); - } - - // ensure the node still exists before deleting - if (this.getNodeService().exists(node.getNodeRef())) - { - this.getNodeService().deleteNode(nodeRef); - } - - tx.commit(); - } - catch (Throwable err) - { - try { if (tx != null) {tx.rollback();} } catch (Exception ex) {} - } - } - } - } - finally - { - if (isAdmin && !this.executeRules) - { - Repository.getServiceRegistry(context).getRuleService().enableRules(); - } - } - } - else - { - logger.warn("WARNING: delete called without a current Space!"); - } - - return outcome; - } - - @Override - protected String doPostCommitProcessing(FacesContext context, String outcome) - { - Node node = this.browseBean.getActionSpace(); - - if (node != null && this.getNodeService().exists(node.getNodeRef()) == false) - { - // remove this node from the breadcrumb if required - this.browseBean.removeSpaceFromBreadcrumb(node); - - // clear action context - this.browseBean.setActionSpace(null); - - // setting the outcome will show the browse view again - return AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME + - AlfrescoNavigationHandler.OUTCOME_SEPARATOR + "browse"; - } - else - { - return outcome; - } - } - - @Override - protected String getErrorMessageId() - { - return "error_delete_space"; - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - protected String getConfirmMessageId() - { - return "delete_space_confirm"; - } - - // ------------------------------------------------------------------------------ - // Bean Getters and Setters - - /** - * Returns the confirmation to display to the user before deleting the content. - * - * @return The formatted message to display - */ - public String getConfirmMessage() - { - String fileConfirmMsg = Application.getMessage(FacesContext.getCurrentInstance(), - getConfirmMessageId()); - - Node node = this.browseBean.getActionSpace(); - if (node != null) - { - return MessageFormat.format(fileConfirmMsg, new Object[] {node.getName()}); - } - else - { - return Application.getMessage(FacesContext.getCurrentInstance(), - "delete_node_not_found"); - } - } - - /** - * @return Returns the delete operation mode. - */ - public String getDeleteMode() - { - return this.deleteMode; - } - - /** - * @param deleteMode The delete operation mode to set. - */ - public void setDeleteMode(String deleteMode) - { - this.deleteMode = deleteMode; - } - - /** - * @return true if the space has multiple parents - */ - public boolean getHasMultipleParents() - { - return this.hasMultipleParents; - } - - /** - * @return true to execute rules during delete - */ - public boolean getExecuteRules() - { - return this.executeRules; - } - - /** - * @param executeRules execute rules during delete - */ - public void setExecuteRules(boolean executeRules) - { - this.executeRules = executeRules; - } - - /** - * @return true to archive nodes during delete - */ - public boolean getArchiveNodes() - { - return this.archiveNodes; - } - - /** - * @param archiveNodes archive nodes during delete - */ - public void setArchiveNodes(boolean archiveNodes) - { - this.archiveNodes = archiveNodes; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/spaces/EditSimpleWorkflowDialog.java b/war/src/main/java/org/alfresco/web/bean/spaces/EditSimpleWorkflowDialog.java deleted file mode 100644 index e481964a59..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/spaces/EditSimpleWorkflowDialog.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.spaces; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.HashMap; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.repo.transaction.RetryingTransactionHelper; -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.actions.handlers.SimpleWorkflowHandler; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; - -public class EditSimpleWorkflowDialog extends BaseDialogBean -{ - private static final long serialVersionUID = 5997327694341960824L; - - protected Map workflowProperties; - - private static final String MSG_ERROR_UPDATE_SIMPLEWORKFLOW = "error_update_simpleworkflow"; - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - saveWorkflow(); - return outcome; - } - - public boolean getFinishButtonDisabled() - { - return false; - } - - public String saveWorkflow() - { - String outcome = "cancel"; - - try - { - RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(FacesContext.getCurrentInstance()); - RetryingTransactionCallback callback = new RetryingTransactionCallback() - { - public Object execute() throws Throwable - { - // firstly retrieve all the properties for the current node - Map updateProps = getNodeService().getProperties(getNode().getNodeRef()); - - // update the simple workflow properties - - // set the approve step name - updateProps.put(ApplicationModel.PROP_APPROVE_STEP, workflowProperties.get(SimpleWorkflowHandler.PROP_APPROVE_STEP_NAME)); - - // specify whether the approve step will copy or move the content - boolean approveMove = true; - String approveAction = (String) workflowProperties.get(SimpleWorkflowHandler.PROP_APPROVE_ACTION); - if (approveAction != null && approveAction.equals("copy")) - { - approveMove = false; - } - updateProps.put(ApplicationModel.PROP_APPROVE_MOVE, Boolean.valueOf(approveMove)); - - // create node ref representation of the destination folder - updateProps.put(ApplicationModel.PROP_APPROVE_FOLDER, workflowProperties.get(SimpleWorkflowHandler.PROP_APPROVE_FOLDER)); - - // determine whether there should be a reject step - boolean requireReject = true; - String rejectStepPresent = (String) workflowProperties.get(SimpleWorkflowHandler.PROP_REJECT_STEP_PRESENT); - if (rejectStepPresent != null && rejectStepPresent.equals("no")) - { - requireReject = false; - } - - if (requireReject) - { - // set the reject step name - updateProps.put(ApplicationModel.PROP_REJECT_STEP, workflowProperties.get(SimpleWorkflowHandler.PROP_REJECT_STEP_NAME)); - - // specify whether the reject step will copy or move the content - boolean rejectMove = true; - String rejectAction = (String) workflowProperties.get(SimpleWorkflowHandler.PROP_REJECT_ACTION); - if (rejectAction != null && rejectAction.equals("copy")) - { - rejectMove = false; - } - updateProps.put(ApplicationModel.PROP_REJECT_MOVE, Boolean.valueOf(rejectMove)); - - // create node ref representation of the destination folder - updateProps.put(ApplicationModel.PROP_REJECT_FOLDER, workflowProperties.get(SimpleWorkflowHandler.PROP_REJECT_FOLDER)); - } - else - { - // set all the reject properties to null to signify there should - // be no reject step - updateProps.put(ApplicationModel.PROP_REJECT_STEP, null); - updateProps.put(ApplicationModel.PROP_REJECT_MOVE, null); - updateProps.put(ApplicationModel.PROP_REJECT_FOLDER, null); - } - - // set the properties on the node - getNodeService().setProperties(getNode().getNodeRef(), updateProps); - return null; - } - }; - txnHelper.doInTransaction(callback); - - // reset the state of the current node so it reflects the changes just made - getNode().reset(); - - outcome = "finish"; - } - catch (Throwable e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), MSG_ERROR_UPDATE_SIMPLEWORKFLOW), e.getMessage()), e); - ReportedException.throwIfNecessary(e); - } - - return outcome; - } - - /** - * Returns the properties for the attached workflow as a map - * - * @return Properties of the attached workflow, null if there is no workflow - */ - public Map getWorkflowProperties() - { - if (this.workflowProperties == null && getNode().hasAspect(ApplicationModel.ASPECT_SIMPLE_WORKFLOW)) - { - // get the exisiting properties for the node - Map props = getNode().getProperties(); - - String approveStepName = (String) props.get(ApplicationModel.PROP_APPROVE_STEP.toString()); - String rejectStepName = (String) props.get(ApplicationModel.PROP_REJECT_STEP.toString()); - - Boolean approveMove = (Boolean) props.get(ApplicationModel.PROP_APPROVE_MOVE.toString()); - Boolean rejectMove = (Boolean) props.get(ApplicationModel.PROP_REJECT_MOVE.toString()); - - NodeRef approveFolder = (NodeRef) props.get(ApplicationModel.PROP_APPROVE_FOLDER.toString()); - NodeRef rejectFolder = (NodeRef) props.get(ApplicationModel.PROP_REJECT_FOLDER.toString()); - - // put the workflow properties in a separate map for use by the JSP - this.workflowProperties = new HashMap(7); - this.workflowProperties.put(SimpleWorkflowHandler.PROP_APPROVE_STEP_NAME, approveStepName); - this.workflowProperties.put(SimpleWorkflowHandler.PROP_APPROVE_ACTION, approveMove ? "move" : "copy"); - this.workflowProperties.put(SimpleWorkflowHandler.PROP_APPROVE_FOLDER, approveFolder); - - if (rejectStepName == null || rejectMove == null || rejectFolder == null) - { - this.workflowProperties.put(SimpleWorkflowHandler.PROP_REJECT_STEP_PRESENT, "no"); - } - else - { - this.workflowProperties.put(SimpleWorkflowHandler.PROP_REJECT_STEP_PRESENT, "yes"); - this.workflowProperties.put(SimpleWorkflowHandler.PROP_REJECT_STEP_NAME, rejectStepName); - this.workflowProperties.put(SimpleWorkflowHandler.PROP_REJECT_ACTION, rejectMove ? "move" : "copy"); - this.workflowProperties.put(SimpleWorkflowHandler.PROP_REJECT_FOLDER, rejectFolder); - } - } - - return this.workflowProperties; - } - - public Node getNode() - { - return this.browseBean.getActionSpace(); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/spaces/EditSpaceDialog.java b/war/src/main/java/org/alfresco/web/bean/spaces/EditSpaceDialog.java deleted file mode 100644 index 285a2ee04f..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/spaces/EditSpaceDialog.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.spaces; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.dictionary.DataTypeDefinition; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.cmr.repository.AssociationRef; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; - -/** - * Dialog bean to edit an existing space. - * - * @author gavinc - */ -public class EditSpaceDialog extends CreateSpaceDialog -{ - private static final long serialVersionUID = 6090397957979372269L; - - protected Node editableNode; - - @Override - public void init(Map parameters) - { - super.init(parameters); - - // setup the space being edited - this.editableNode = initEditableNode(); - this.spaceType = this.editableNode.getType().toString(); - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - /** - * Init the editable Node - */ - protected Node initEditableNode() - { - return new Node(this.browseBean.getActionSpace().getNodeRef()); - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "ok"); - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - // update the existing node in the repository - NodeRef nodeRef = this.editableNode.getNodeRef(); - Map editedProps = this.editableNode.getProperties(); - - // handle the name property separately, perform a rename in case it changed - String name = (String)editedProps.get(ContentModel.PROP_NAME); - if (name != null) - { - this.getFileFolderService().rename(nodeRef, name); - } - - // build the properties to add to the repository - Map repoProps = new HashMap(7); - - // overwrite the current properties with the edited ones - Iterator iterProps = editedProps.keySet().iterator(); - while (iterProps.hasNext()) - { - String propName = iterProps.next(); - QName qname = QName.createQName(propName); - - // make sure the property is represented correctly - Serializable propValue = (Serializable)editedProps.get(propName); - - // check for empty strings when using number types, set to null in this case - if ((propValue != null) && (propValue instanceof String) && - (propValue.toString().length() == 0)) - { - PropertyDefinition propDef = this.getDictionaryService().getProperty(qname); - if (propDef != null) - { - if (propDef.getDataType().getName().equals(DataTypeDefinition.DOUBLE) || - propDef.getDataType().getName().equals(DataTypeDefinition.FLOAT) || - propDef.getDataType().getName().equals(DataTypeDefinition.INT) || - propDef.getDataType().getName().equals(DataTypeDefinition.LONG)) - { - propValue = null; - } - } - } - - repoProps.put(qname, propValue); - } - - // add the new properties back to the repository - this.getNodeService().addProperties(nodeRef, repoProps); - - // we also need to persist any association changes that may have been made - - // add any associations added in the UI - Map> addedAssocs = this.editableNode.getAddedAssociations(); - for (Map typedAssoc : addedAssocs.values()) - { - for (AssociationRef assoc : typedAssoc.values()) - { - this.getNodeService().createAssociation(assoc.getSourceRef(), assoc.getTargetRef(), assoc.getTypeQName()); - } - } - - // remove any association removed in the UI - Map> removedAssocs = this.editableNode.getRemovedAssociations(); - for (Map typedAssoc : removedAssocs.values()) - { - for (AssociationRef assoc : typedAssoc.values()) - { - this.getNodeService().removeAssociation(assoc.getSourceRef(), assoc.getTargetRef(), assoc.getTypeQName()); - } - } - - // add any child associations added in the UI - Map> addedChildAssocs = this.editableNode.getAddedChildAssociations(); - for (Map typedAssoc : addedChildAssocs.values()) - { - for (ChildAssociationRef assoc : typedAssoc.values()) - { - this.getNodeService().addChild(assoc.getParentRef(), assoc.getChildRef(), assoc.getTypeQName(), assoc.getTypeQName()); - } - } - - // remove any child association removed in the UI - Map> removedChildAssocs = this.editableNode.getRemovedChildAssociations(); - for (Map typedAssoc : removedChildAssocs.values()) - { - for (ChildAssociationRef assoc : typedAssoc.values()) - { - this.getNodeService().removeChild(assoc.getParentRef(), assoc.getChildRef()); - } - } - - // do nothing by default, subclasses can override if necessary - return AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME; - } - - @Override - protected String doPostCommitProcessing(FacesContext context, String outcome) - { - this.browseBean.getActionSpace().reset(); - - return outcome; - } - - - // ------------------------------------------------------------------------------ - // Bean getters and setters - - /** - * Returns the node being edited - * - * @return The node being edited - */ - public Node getEditableNode() - { - return this.editableNode; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/spaces/InviteSpaceUsersWizard.java b/war/src/main/java/org/alfresco/web/bean/spaces/InviteSpaceUsersWizard.java deleted file mode 100644 index 6347479175..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/spaces/InviteSpaceUsersWizard.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.spaces; - -import java.util.Set; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.wizard.BaseInviteUsersWizard; - -/** - * Concrete implementation providing the ability to invite users to a space. - * - * @author gavinc - */ -public class InviteSpaceUsersWizard extends BaseInviteUsersWizard -{ - private static final long serialVersionUID = -1584891656721183347L; - - @Override - protected Set getPermissionsForType() - { - // Let the permission service do the caching to allow for dynamic model updates, etc. - return this.permissionService.getSettablePermissions(getNode().getType()); - } - - @Override - protected Node getNode() - { - return this.browseBean.getActionSpace(); - } - - @Override - protected String getEmailTemplateXPath() - { - FacesContext fc = FacesContext.getCurrentInstance(); - String xpath = Application.getRootPath(fc) + "/" + - Application.getGlossaryFolderName(fc) + "/" + - Application.getEmailTemplatesFolderName(fc) + "/" + - Application.getInviteEmailTemplatesFolderName(fc) + "//*"; - return xpath; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/spaces/RecentSpacesBean.java b/war/src/main/java/org/alfresco/web/bean/spaces/RecentSpacesBean.java deleted file mode 100644 index 41be94b130..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/spaces/RecentSpacesBean.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.spaces; - -import java.text.MessageFormat; -import java.util.LinkedList; -import java.util.List; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.IContextListener; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.bean.BrowseBean; -import org.alfresco.web.bean.NavigationBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.config.ClientConfigElement; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.repo.component.shelf.UIRecentSpacesShelfItem; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * This bean manages the real-time updated list of Recent Spaces in the Shelf component. - *

- * Registers itself as a UI Context Listener so it is informed as to when the current Node ID - * has changed in the NavigationBeans. This is used to keep the list of spaces up-to-date. - * - * @author Kevin Roast - */ -public class RecentSpacesBean implements IContextListener -{ - private static final long serialVersionUID = -6405913558933664909L; - - private static Log logger = LogFactory.getLog(RecentSpacesBean.class); - - /** The NavigationBean reference */ - protected NavigationBean navigator; - - /** The BrowseBean reference */ - protected BrowseBean browseBean; - - /** Maximum number of recent spaces to show */ - private Integer maxRecentSpaces = null; - - /** List of recent space nodes */ - private List recentSpaces = new LinkedList(); - - - // ------------------------------------------------------------------------------ - // Construction - - /** - * Default Constructor - */ - public RecentSpacesBean() - { - UIContextService.getInstance(FacesContext.getCurrentInstance()).registerBean(this); - } - - - // ------------------------------------------------------------------------------ - // Bean property getters and setters - - /** - * @param navigator The NavigationBean to set. - */ - public void setNavigator(NavigationBean navigator) - { - this.navigator = navigator; - } - - /** - * @param browseBean The BrowseBean to set. - */ - public void setBrowseBean(BrowseBean browseBean) - { - this.browseBean = browseBean; - } - - /** - * @return the List of recent spaces - */ - public List getRecentSpaces() - { - return this.recentSpaces; - } - - /** - * @param spaces List of Nodes - */ - public void setRecentSpaces(List spaces) - { - this.recentSpaces = spaces; - } - - - // ------------------------------------------------------------------------------ - // Action method handlers - - /** - * Action handler bound to the recent spaces Shelf component called when a Space is clicked - */ - public void navigate(ActionEvent event) - { - // work out which node was clicked from the event data - UIRecentSpacesShelfItem.RecentSpacesEvent spaceEvent = (UIRecentSpacesShelfItem.RecentSpacesEvent)event; - Node selectedNode = this.recentSpaces.get(spaceEvent.Index); - NodeRef nodeRef = selectedNode.getNodeRef(); - try - { - // then navigate to the appropriate node in UI - // use browse bean functionality for this as it will update the breadcrumb for us - this.browseBean.updateUILocation(nodeRef); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {nodeRef.getId()}) ); - - // remove invalid node from recent spaces list - this.recentSpaces.remove(spaceEvent.Index); - } - } - - - // ------------------------------------------------------------------------------ - // IContextListener implementation - - /** - * @see org.alfresco.web.app.context.IContextListener#contextUpdated() - */ - public void contextUpdated() - { - // We use this listener handler to refresh the recent spaces list. At the point - // where this method is called, the current node Id in UI will probably have changed. - Node node = this.navigator.getCurrentNode(); - - // search for this node - if it's already in the list remove it so - // that it appears at the top for us - for (int i=0; i. - * #L% - */ -package org.alfresco.web.bean.spaces; - -import java.text.MessageFormat; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.TemplateService; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.servlet.GuestTemplateContentServlet; -import org.alfresco.web.bean.BaseDetailsBean; -import org.alfresco.web.bean.TemplateSupportBean; -import org.alfresco.web.bean.dialog.NavigationSupport; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.NodeListUtils; -import org.alfresco.web.ui.common.NodePropertyComparator; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.Utils.URLMode; -import org.alfresco.web.ui.common.component.UIActionLink; - -/** - * Backing bean provided access to the details of a Space - * - * @author Kevin Roast - */ -public class SpaceDetailsDialog extends BaseDetailsBean implements NavigationSupport -{ - private static final long serialVersionUID = -6066782024875635443L; - - private static final String MSG_HAS_FOLLOWING_CATEGORIES = "has_following_categories_space"; - private static final String MSG_NO_CATEGORIES_APPLIED = "no_categories_applied_space"; - private static final String MSG_ERROR_ASPECT_CLASSIFY = "error_aspect_classify_space"; - private static final String MSG_DETAILS_OF = "details_of"; - private static final String MSG_LOCATION = "location"; - private final static String MSG_CLOSE = "close"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - /** RSS Template ID */ - private String rssTemplate; - - // ------------------------------------------------------------------------------ - // Construction - - /** - * Default constructor - */ - public SpaceDetailsDialog() - { - super(); - - // initial state of some panels that don't use the default - panels.put("rules-panel", false); - panels.put("dashboard-panel", false); - } - - - // ------------------------------------------------------------------------------ - // Bean property getters and setters - - /** - * Returns the Node this bean is currently representing - * - * @return The Node - */ - public Node getNode() - { - return this.browseBean.getActionSpace(); - } - - /** - * Returns the Space this bean is currently representing - * - * @return The Space Node - */ - public Node getSpace() - { - return getNode(); - } - - /** - * Returns the URL to access the browse page for the current node - * - * @return The bookmark URL - */ - public String getBrowseUrl() - { - return Utils.generateURL(FacesContext.getCurrentInstance(), getNode(), URLMode.BROWSE); - } - - /** - * Resolve the actual document Node from any Link object that may be proxying it - * - * @return current document Node or document Node resolved from any Link object - */ - protected Node getLinkResolvedNode() - { - Node space = getSpace(); - if (ApplicationModel.TYPE_FOLDERLINK.equals(space.getType())) - { - NodeRef destRef = (NodeRef)space.getProperties().get(ContentModel.PROP_LINK_DESTINATION); - if (getNodeService().exists(destRef)) - { - space = new Node(destRef); - } - } - return space; - } - - /** - * Returns a model for use by a template on the Space Details page. - * - * @return model containing current current space info. - */ - @SuppressWarnings("unchecked") - public Map getTemplateModel() - { - HashMap model = new HashMap(1, 1.0f); - - model.put("space", getSpace().getNodeRef()); - model.put(TemplateService.KEY_IMAGE_RESOLVER, imageResolver); - - return model; - } - - /** - * @see org.alfresco.web.bean.BaseDetailsBean#getPropertiesPanelId() - */ - protected String getPropertiesPanelId() - { - return "space-props"; - } - - - // ------------------------------------------------------------------------------ - // Action event handlers - - /** - * Navigates to next item in the list of Spaces - */ - public void nextItem(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - NodeRef currNodeRef = new NodeRef(Repository.getStoreRef(), id); - List nodes = this.browseBean.getParentNodes(currNodeRef); - Node next = null; - if (nodes.size() > 1) - { - String currentSortColumn = this.browseBean.getSpacesRichList().getCurrentSortColumn(); - if (currentSortColumn != null) - { - boolean currentSortDescending = this.browseBean.getSpacesRichList().isCurrentSortDescending(); - Collections.sort(nodes, new NodePropertyComparator(currentSortColumn, !currentSortDescending)); - } - next = NodeListUtils.nextItem(nodes, id); - this.browseBean.setupSpaceAction(next.getId(), false); - } - if (next == null) - { - Node currNode = new Node(currNodeRef); - this.navigator.setupDispatchContext(currNode); - } - } - } - - /** - * Navigates to the previous item in the list Spaces - */ - public void previousItem(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - NodeRef currNodeRef = new NodeRef(Repository.getStoreRef(), id); - List nodes = this.browseBean.getParentNodes(currNodeRef); - Node previous = null; - if (nodes.size() > 1) - { - String currentSortColumn = this.browseBean.getSpacesRichList().getCurrentSortColumn(); - if (currentSortColumn != null) - { - boolean currentSortDescending = this.browseBean.getSpacesRichList().isCurrentSortDescending(); - Collections.sort(nodes, new NodePropertyComparator(currentSortColumn, !currentSortDescending)); - } - previous = NodeListUtils.previousItem(nodes, id); - this.browseBean.setupSpaceAction(previous.getId(), false); - } - if (previous == null) - { - Node currNode = new Node(currNodeRef); - this.navigator.setupDispatchContext(currNode); - } - } - } - - /** - * Action handler to clear the current Space properties before returning to the browse screen, - * as the user may have modified the properties! - */ - public String cancel() - { - this.navigator.resetCurrentNodeProperties(); - return super.cancel(); - } - - // ------------------------------------------------------------------------------ - // Categorised Details - - /** - * Determines whether the current space has any categories applied - * - * @return true if the document has categories attached - */ - public boolean isCategorised() - { - return getSpace().hasAspect(ContentModel.ASPECT_GEN_CLASSIFIABLE); - } - - /** - * Returns a list of objects representing the categories applied to the - * current space - * - * @return List of categories - */ - public String getCategoriesOverviewHTML() - { - String html = null; - - if (isCategorised()) - { - // we know for now that the general classifiable aspect only will be - // applied so we can retrive the categories property direclty - Collection categories = (Collection)getNodeService().getProperty( - getSpace().getNodeRef(), ContentModel.PROP_CATEGORIES); - - if (categories == null || categories.size() == 0) - { - html = Application.getMessage(FacesContext.getCurrentInstance(), MSG_NO_CATEGORIES_APPLIED); - } - else - { - StringBuilder builder = new StringBuilder(Application.getMessage(FacesContext.getCurrentInstance(), - MSG_HAS_FOLLOWING_CATEGORIES)); - - builder.append("

    "); - for (NodeRef ref : categories) - { - if (getNodeService().exists(ref)) - { - builder.append("
  • "); - builder.append(Repository.getNameForNode(getNodeService(), ref)); - builder.append("
  • "); - } - } - builder.append("
"); - - html = builder.toString(); - } - } - - return html; - } - - /** - * Applies the classifiable aspect to the current document - */ - public void applyClassifiable() - { - UserTransaction tx = null; - - try - { - tx = Repository.getUserTransaction(FacesContext.getCurrentInstance()); - tx.begin(); - - // add the general classifiable aspect to the node - getNodeService().addAspect(getSpace().getNodeRef(), ContentModel.ASPECT_GEN_CLASSIFIABLE, null); - - // commit the transaction - tx.commit(); - - // reset the state of the current document - getSpace().reset(); - } - catch (Throwable e) - { - // rollback the transaction - try { if (tx != null) {tx.rollback();} } catch (Exception ex) {} - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), MSG_ERROR_ASPECT_CLASSIFY), e.getMessage()), e); - } - } - - /** - * Returns whether the current sapce is locked - * - * @return true if the document is checked out - */ - public boolean isLocked() - { - return getSpace().isLocked(); - } - - /** - * @return true if the current space has an RSS feed applied - */ - public boolean isRSSFeed() - { - return hasRSSFeed(getSpace()); - } - - /** - * @return true if the current space has an RSS feed applied - */ - public static boolean hasRSSFeed(Node space) - { - return (space.hasAspect(ApplicationModel.ASPECT_FEEDSOURCE) && - space.getProperties().get(ApplicationModel.PROP_FEEDTEMPLATE) != null); - } - - /** - * @return RSS Feed URL for the current space - */ - public String getRSSFeedURL() - { - return buildRSSFeedURL(getSpace()); - } - - /** - * Build URL for an RSS space based on the 'feedsource' aspect property. - * - * @param space Node to build RSS template URL for - * - * @return URL for the RSS feed for a space - */ - public static String buildRSSFeedURL(Node space) - { - // build RSS feed template URL from selected template and the space NodeRef and - // add the guest=true URL parameter - this is required for no login access and - // add the mimetype=text/xml URL parameter - required to return correct stream type - return GuestTemplateContentServlet.generateURL(space.getNodeRef(), - (NodeRef)space.getProperties().get(ApplicationModel.PROP_FEEDTEMPLATE)) - + "/rss.xml?mimetype=text%2Fxml%3Bcharset=utf-8"; - } - - /** - * @return Returns the current RSS Template ID. - */ - public String getRSSTemplate() - { - // return current template if it exists - NodeRef ref = (NodeRef)getNode().getProperties().get(ApplicationModel.PROP_FEEDTEMPLATE); - return ref != null ? ref.getId() : this.rssTemplate; - } - - /** - * @param rssTemplate The RSS Template Id to set. - */ - public void setRSSTemplate(String rssTemplate) - { - this.rssTemplate = rssTemplate; - } - - /** - * Action handler to apply the selected RSS Template and FeedSource aspect to the current Space - */ - public void applyRSSTemplate(ActionEvent event) - { - if (this.rssTemplate != null && this.rssTemplate.equals(TemplateSupportBean.NO_SELECTION) == false) - { - try - { - // apply the feedsource aspect if required - if (getNode().hasAspect(ApplicationModel.ASPECT_FEEDSOURCE) == false) - { - getNodeService().addAspect(getNode().getNodeRef(), ApplicationModel.ASPECT_FEEDSOURCE, null); - } - - // get the selected template Id from the Template Picker - NodeRef templateRef = new NodeRef(Repository.getStoreRef(), this.rssTemplate); - - // set the template NodeRef into the templatable aspect property - getNodeService().setProperty(getNode().getNodeRef(), ApplicationModel.PROP_FEEDTEMPLATE, templateRef); - - // reset node details for next refresh of details page - getNode().reset(); - } - catch (Exception e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), e.getMessage()), e); - } - } - } - - /** - * Action handler to remove a RSS template from the current Space - */ - public void removeRSSTemplate(ActionEvent event) - { - try - { - // clear template property - getNodeService().setProperty(getNode().getNodeRef(), ApplicationModel.PROP_FEEDTEMPLATE, null); - getNodeService().removeAspect(getNode().getNodeRef(), ApplicationModel.ASPECT_FEEDSOURCE); - - // reset node details for next refresh of details page - getNode().reset(); - } - catch (Exception e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), e.getMessage()), e); - } - } - - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - public String getCurrentItemId() - { - return getId(); - } - - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } - - @Override - public String getContainerSubTitle() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_LOCATION) + ": " + - getSpace().getNodePath().toDisplayPath(getNodeService(), getPermissionService()); - } - - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_DETAILS_OF) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) + getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - public String getOutcome(){ - return "dialog:close:dialog:showSpaceDetails"; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanDeleteAllItemsDialog.java b/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanDeleteAllItemsDialog.java deleted file mode 100644 index b592f40aad..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanDeleteAllItemsDialog.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.trashcan; - -import java.text.MessageFormat; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; - -public class TrashcanDeleteAllItemsDialog extends TrashcanDialog -{ - private static final long serialVersionUID = 2537803727179629546L; - - private static final String MSG_YES = "yes"; - private static final String MSG_NO = "no"; - - private String deleteAllItems(FacesContext context, String outcome) - { - if (property.isInProgress()) - return null; - - property.setInProgress(true); - - try - { - property.getNodeArchiveService().purgeAllArchivedNodes(Repository.getStoreRef()); - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, Repository.ERROR_GENERIC), err.getMessage()), err); - ReportedException.throwIfNecessary(err); - } - finally - { - property.setInProgress(false); - } - - return outcome; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return deleteAllItems(context, outcome); - - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_NO); - } - - @Override - public boolean getFinishButtonDisabled() - { - - return false; - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_YES); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanDeleteItemDialog.java b/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanDeleteItemDialog.java deleted file mode 100644 index bb843de2e6..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanDeleteItemDialog.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.trashcan; - -import java.text.MessageFormat; - -import javax.faces.application.FacesMessage; -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; - -public class TrashcanDeleteItemDialog extends TrashcanDialog -{ - private static final long serialVersionUID = 519967126630923155L; - - private static final String RICHLIST_ID = "trashcan-list"; - private static final String RICHLIST_MSG_ID = "trashcan" + ':' + RICHLIST_ID; - private static final String MSG_YES = "yes"; - private static final String MSG_NO = "no"; - private static final String MSG_DELETE_ITEM = "delete_item"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - private String deleteItem(FacesContext newContext, String newOutcome) - { - Node item = property.getItem(); - if (item != null) - { - try - { - property.getNodeArchiveService().purgeArchivedNode(item.getNodeRef()); - - FacesContext fc = newContext; - String msg = MessageFormat.format(Application.getMessage(fc, "delete_item_success"), item.getName()); - FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg); - fc.addMessage(RICHLIST_MSG_ID, facesMsg); - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(newContext, Repository.ERROR_GENERIC), err.getMessage()), err); - ReportedException.throwIfNecessary(err); - } - } - return newOutcome; - } - - @Override - protected String getDefaultFinishOutcome() - { - return "dialog:close[2]"; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return deleteItem(context, outcome); - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_NO); - } - - @Override - public boolean getFinishButtonDisabled() - { - - return false; - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_YES); - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_DELETE_ITEM) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) - + property.getItem().getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanDeleteListedItemsDialog.java b/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanDeleteListedItemsDialog.java deleted file mode 100644 index 9badde826d..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanDeleteListedItemsDialog.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.trashcan; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.List; - -import javax.faces.context.FacesContext; - -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; - -public class TrashcanDeleteListedItemsDialog extends TrashcanDialog -{ - private static final long serialVersionUID = 5576836588148974609L; - - private static final String MSG_YES = "yes"; - private static final String MSG_NO = "no"; - - private String deleteListedItems(FacesContext context, String outcome) - { - if (property.isInProgress()) - return null; - - property.setInProgress(true); - - try - { - List nodeRefs = new ArrayList(property.getListedItems().size()); - for (Node node : property.getListedItems()) - { - nodeRefs.add(node.getNodeRef()); - } - property.getNodeArchiveService().purgeArchivedNodes(nodeRefs); - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, Repository.ERROR_GENERIC), err.getMessage()), err); - ReportedException.throwIfNecessary(err); - } - finally - { - property.setInProgress(false); - } - - return outcome; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return deleteListedItems(context, outcome); - - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_NO); - } - - @Override - public boolean getFinishButtonDisabled() - { - - return false; - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_YES); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanDialog.java b/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanDialog.java deleted file mode 100644 index f0dbfea34c..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanDialog.java +++ /dev/null @@ -1,906 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.trashcan; - -import java.text.MessageFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.node.archive.RestoreNodeReport; -import org.alfresco.repo.node.archive.RestoreNodeReport.RestoreStatus; -import org.alfresco.repo.web.scripts.FileTypeImageUtils; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.ContentData; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.search.ResultSet; -import org.alfresco.service.cmr.search.ResultSetRow; -import org.alfresco.service.cmr.search.SearchParameters; -import org.alfresco.service.cmr.search.SearchService; -import org.alfresco.service.cmr.security.AccessStatus; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.namespace.QName; -import org.alfresco.util.CachingDateFormat; -import org.alfresco.util.SearchLanguageConversion; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.IContextListener; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.bean.BrowseBean; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.MapNode; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.NodePropertyResolver; -import org.alfresco.web.bean.repository.QNameNodeMap; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.spaces.CreateSpaceWizard; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.Utils.URLMode; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.alfresco.web.ui.common.component.UIModeList; - -/** - * Backing bean for the Manage Deleted Items (soft delete and archiving) pages. - * - * @author Kevin Roast - */ -public class TrashcanDialog extends BaseDialogBean implements IContextListener -{ - private static final long serialVersionUID = -7783683979079046969L; - - protected TrashcanDialogProperty property; - - private static final String MSG_DELETED_ITEMS_FOR = "deleted_items_for"; - private static final String MSG_DELETED_ITEMS = "deleted_items"; - private static final String MSG_RECOVERED_ITEM_DUPLICATE_S = "recovered_item_duplicate_short"; - private static final String MSG_RECOVERED_ITEM_INTEGRITY_S = "recovered_item_integrity_short"; - private static final String MSG_RECOVERED_ITEM_PERMISSION_S = "recovered_item_permission_short"; - private static final String MSG_RECOVERED_ITEM_PARENT_S = "recovered_item_parent_short"; - private static final String MSG_RECOVERED_ITEM_FAILURE_S = "recovered_item_failure_short"; - private static final String MSG_RECOVERY_REASON = "recovery_report_reason"; - private static final String MSG_LOCATION = "location"; - private static final String MSG_NAME = "name"; - private final static String MSG_CLOSE = "close"; - - private static final String PROP_RECOVERSTATUS = "recoverstatus"; - private static final String PROP_RECOVERERRORMESSAGE = "recovererrormessage"; - - private static final String FILTER_DATE_ALL = "all"; - private static final String FILTER_DATE_TODAY = "today"; - private static final String FILTER_DATE_WEEK = "week"; - private static final String FILTER_DATE_MONTH = "month"; - private static final String FILTER_USER_USER = "user"; - - private static final String OUTCOME_DIALOGCLOSE = "dialog:close"; - - private final static String NAME_ATTR = Repository.escapeQName(ContentModel.PROP_NAME); - private final static String USER_ATTR = Repository.escapeQName(ContentModel.PROP_ARCHIVED_BY); - private final static String DATE_ATTR = Repository.escapeQName(ContentModel.PROP_ARCHIVED_DATE); - - private final static String SEARCH_ALL = "PARENT:\"%s\" AND ASPECT:\"%s\""; - private final static String SEARCH_NAME = "PARENT:\"%s\" AND ASPECT:\"%s\" AND (@" + NAME_ATTR + ":*%s* @" + NAME_ATTR + ":\"*%s*\")"; - private final static String SEARCH_TEXT = "PARENT:\"%s\" AND ASPECT:\"%s\" AND TEXT:%s"; - private final static String SEARCH_NAME_QUOTED = "PARENT:\"%s\" AND ASPECT:\"%s\" AND @" + NAME_ATTR + ":\"%s\""; - private final static String SEARCH_TEXT_QUOTED = "PARENT:\"%s\" AND ASPECT:\"%s\" AND TEXT:\"%s\""; - private final static String SEARCH_USERPREFIX = "@" + USER_ATTR + ":%s AND "; - - /** maximum number of failed items to report to the user */ - private static final int MAX_FAILURE_REPORTS = 25; - - /** The PermissionService reference */ - transient protected PermissionService permissionService; - - - /** - * @param permissionService The PermissionService to set. - */ - public void setPermissionService(PermissionService permissionService) - { - this.permissionService = permissionService; - } - - protected PermissionService getPermissionService() - { - if (permissionService == null) - { - permissionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPermissionService(); - } - return permissionService; - } - - public void setProperty(TrashcanDialogProperty property) - { - this.property = property; - } - - public TrashcanDialogProperty getProperty() - { - return property; - } - - /** - * @return Message to display in the title of the panel area - */ - public String getPanelMessage() - { - FacesContext fc = FacesContext.getCurrentInstance(); - String msg = Application.getMessage(fc, MSG_DELETED_ITEMS); - if (isAdminUser() == false) - { - msg = msg + ' ' + MessageFormat.format( - Application.getMessage(fc, MSG_DELETED_ITEMS_FOR), Application.getCurrentUser(fc).getUserName()); - } - return msg; - } - - /** - * Returns the URL to the content for the current document item - * - * @return Content url to the current document item - */ - public String getItemBrowserUrl() - { - return Utils.generateURL(FacesContext.getCurrentInstance(), property.getItem(), URLMode.HTTP_INLINE); - } - - /** - * Returns the download URL to the content for the current document item - * - * @return Download url to the current document item - */ - public String getItemDownloadUrl() - { - return Utils.generateURL(FacesContext.getCurrentInstance(), property.getItem(), URLMode.HTTP_DOWNLOAD); - } - - /** - * Return the Alfresco NodeRef URL for the current item node - * - * @return the Alfresco NodeRef URL - */ - public String getItemNodeRefUrl() - { - return property.getItem().getNodeRef().toString(); - } - - /** - * @return HTML table of the listed items - */ - public String getListedItemsTable() - { - return buildItemsTable(property.getListedItems(), "recoveredItemsList", false, true); - } - - /** - * @return HTML table of the items successfully recovered - */ - public String getSuccessItemsTable() - { - return buildItemsTable(property.getSuccessItems(), "recoveredItemsList", false, false); - } - - /** - * @return HTML table of the items that failed to recover - */ - public String getFailureItemsTable() - { - return buildItemsTable(property.getFailureItems(), "failedItemsList", true, false); - } - - /** - * @return the list of deleted items to display - */ - public List getItems() - { - // to get deleted items from deleted items store - // use a search to find the items - also filters by name/username - List itemNodes = null; - - UserTransaction tx = null; - ResultSet results = null; - try - { - tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true); - tx.begin(); - - // get the root node to the deleted items store - if (getArchiveRootRef() != null && property.isShowItems()) - { - String query = buildSearchQuery(); - SearchParameters sp = new SearchParameters(); - sp.setLanguage(SearchService.LANGUAGE_LUCENE); - sp.setQuery(query); - sp.addStore(getArchiveRootRef().getStoreRef()); // the Archived Node store - - results = getSearchService().query(sp); - itemNodes = new ArrayList(results.length()); - } - - if (results != null && results.length() != 0) - { - for (ResultSetRow row : results) - { - NodeRef nodeRef = row.getNodeRef(); - - if (getNodeService().exists(nodeRef)) - { - QName type = getNodeService().getType(nodeRef); - - MapNode node = new MapNode(nodeRef, getNodeService(), false); - - node.addPropertyResolver("locationPath", resolverLocationPath); - node.addPropertyResolver("displayPath", resolverDisplayPath); - node.addPropertyResolver("deletedDate", resolverDeletedDate); - node.addPropertyResolver("deletedBy", resolverDeletedBy); - node.addPropertyResolver("isFolder", resolverIsFolder); - - if (getDictionaryService().isSubClass(type, ContentModel.TYPE_FOLDER) == true && - getDictionaryService().isSubClass(type, ContentModel.TYPE_SYSTEM_FOLDER) == false) - { - node.addPropertyResolver("typeIcon", this.resolverSmallIcon); - } - else - { - node.addPropertyResolver("typeIcon", this.resolverFileType16); - } - itemNodes.add(node); - } - } - } - - tx.commit(); - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), new Object[] {err.getMessage()}), err ); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - finally - { - if (results != null) - { - results.close(); - } - } - - property.setListedItems((itemNodes != null ? itemNodes : Collections. emptyList())); - - return property.getListedItems(); - } - - private NodePropertyResolver resolverLocationPath = new NodePropertyResolver() - { - private static final long serialVersionUID = -2501720368642759082L; - - public Object get(Node node) - { - ChildAssociationRef childRef = (ChildAssociationRef)node.getProperties().get(ContentModel.PROP_ARCHIVED_ORIGINAL_PARENT_ASSOC); - if (getPermissionService().hasPermission(childRef.getParentRef(), PermissionService.READ).equals(AccessStatus.ALLOWED) && - getNodeService().exists(childRef.getParentRef())) - { - return getNodeService().getPath(childRef.getParentRef()); - } - else - { - return null; - } - } - }; - - private NodePropertyResolver resolverDisplayPath = new NodePropertyResolver() - { - private static final long serialVersionUID = 9178556770343499694L; - - public Object get(Node node) - { - ChildAssociationRef childRef = (ChildAssociationRef)node.getProperties().get(ContentModel.PROP_ARCHIVED_ORIGINAL_PARENT_ASSOC); - if (getPermissionService().hasPermission(childRef.getParentRef(), PermissionService.READ).equals(AccessStatus.ALLOWED) && - getNodeService().exists(childRef.getParentRef())) - { - return Repository.getDisplayPath(getNodeService().getPath(childRef.getParentRef()), true); - } - else - { - return ""; - } - } - }; - - private NodePropertyResolver resolverFileType16 = new NodePropertyResolver() - { - private static final long serialVersionUID = 7462526266770371703L; - - public Object get(Node node) - { - return FileTypeImageUtils.getFileTypeImage(node.getName(), true); - } - }; - - private NodePropertyResolver resolverSmallIcon = new NodePropertyResolver() - { - private static final long serialVersionUID = 5528945140207247127L; - - @SuppressWarnings("unchecked") - public Object get(Node node) - { - QNameNodeMap props = (QNameNodeMap)node.getProperties(); - String icon = (String) props.getRaw("app:icon"); - return "/images/icons/" + (icon != null ? icon + "-16.gif" : BrowseBean.SPACE_SMALL_DEFAULT + ".gif"); - } - }; - - private NodePropertyResolver resolverFileType32 = new NodePropertyResolver() - { - private static final long serialVersionUID = -5681639025578263060L; - - public Object get(Node node) - { - return FileTypeImageUtils.getFileTypeImage(node.getName(), false); - } - }; - - private NodePropertyResolver resolverLargeIcon = new NodePropertyResolver() - { - private static final long serialVersionUID = -8334570770580388654L; - - @SuppressWarnings("unchecked") - public Object get(Node node) - { - QNameNodeMap props = (QNameNodeMap)node.getProperties(); - String icon = (String) props.getRaw("app:icon"); - return "/images/icons/" + (icon != null ? icon : CreateSpaceWizard.DEFAULT_SPACE_ICON_NAME) + ".gif"; - } - }; - - private NodePropertyResolver resolverMimetype = new NodePropertyResolver() - { - private static final long serialVersionUID = -5892550146037635522L; - - public Object get(Node node) - { - ContentData content = (ContentData)node.getProperties().get(ContentModel.PROP_CONTENT); - return (content != null ? content.getMimetype() : null); - } - }; - - private NodePropertyResolver resolverSize = new NodePropertyResolver() - { - private static final long serialVersionUID = -191591211947393578L; - - public Object get(Node node) - { - ContentData content = (ContentData)node.getProperties().get(ContentModel.PROP_CONTENT); - return (content != null ? new Long(content.getSize()) : 0L); - } - }; - - private NodePropertyResolver resolverEncoding = new NodePropertyResolver() - { - private static final long serialVersionUID = -1594354572323978873L; - - public Object get(Node node) - { - ContentData content = (ContentData)node.getProperties().get(ContentModel.PROP_CONTENT); - return (content != null ? content.getEncoding() : null); - } - }; - - private NodePropertyResolver resolverDeletedDate = new NodePropertyResolver() - { - private static final long serialVersionUID = 3240286507786251191L; - - public Object get(Node node) - { - return node.getProperties().get(ContentModel.PROP_ARCHIVED_DATE); - } - }; - - private NodePropertyResolver resolverDeletedBy = new NodePropertyResolver() - { - private static final long serialVersionUID = -8678755146743606599L; - - public Object get(Node node) - { - return node.getProperties().get(ContentModel.PROP_ARCHIVED_BY); - } - }; - - private NodePropertyResolver resolverIsFolder = new NodePropertyResolver() - { - private static final long serialVersionUID = -9181535522349485509L; - - public Object get(Node node) - { - return getDictionaryService().isSubClass(node.getType(), ContentModel.TYPE_FOLDER); - } - }; - - - // ------------------------------------------------------------------------------ - // Action handlers - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - /** - * Search the deleted item store by name - */ - public void searchName(ActionEvent event) - { - // simply clear the current list and refresh the screen - // the search query text will be found and processed by the getItems() method - contextUpdated(); - property.setShowItems(true); - property.setFullTextSearch(false); - } - - /** - * Search the deleted item store by text - */ - public void searchContent(ActionEvent event) - { - // simply clear the current list and refresh the screen - // the search query text will be found and processed by the getItems() method - contextUpdated(); - property.setShowItems(true); - property.setFullTextSearch(true); - } - - /** - * Action handler to clear the current search results and show all items - */ - public void clearSearch(ActionEvent event) - { - contextUpdated(); - property.setSearchText(null); - property.setShowItems(true); - } - - /** - * Action handler called to prepare the selected item for an action - */ - public void setupItemAction(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - try - { - // create the node ref, then our node representation - NodeRef ref = new NodeRef(getArchiveRootRef().getStoreRef(), id); - Node node = new Node(ref); - - node.addPropertyResolver("locationPath", resolverLocationPath); - node.addPropertyResolver("deletedDate", resolverDeletedDate); - node.addPropertyResolver("deletedBy", resolverDeletedBy); - node.addPropertyResolver("isFolder", resolverIsFolder); - node.addPropertyResolver("mimetype", resolverMimetype); - node.addPropertyResolver("size", resolverSize); - node.addPropertyResolver("encoding", resolverEncoding); - - if (getDictionaryService().isSubClass(node.getType(), ContentModel.TYPE_FOLDER) == true && - getDictionaryService().isSubClass(node.getType(), ContentModel.TYPE_SYSTEM_FOLDER) == false) - { - node.addPropertyResolver("icon", this.resolverLargeIcon); - } - else - { - node.addPropertyResolver("icon", this.resolverFileType32); - } - - // prepare a node for the action context - property.setItem(node); - property.setDestination(null); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {id})); - } - } - else - { - property.setItem(null); - } - - // clear the UI state in preparation for finishing the next action - contextUpdated(); - } - - /** - * Action handler to setup actions that act on lists - */ - public void setupListAction(ActionEvent event) - { - // clear the UI state in preparation for finishing the next action - property.setDestination(null); - contextUpdated(); - } - - /** - * @return outcome to close the main list screen and reset other beans ready for display - */ - public String close() - { - // call beans to update UI context for other screens - UIContextService.getInstance(FacesContext.getCurrentInstance()).notifyBeans(); - return OUTCOME_DIALOGCLOSE; - } - - /** - * Action handler to initially setup the trashcan screen - */ - public void setupTrashcan(ActionEvent event) - { - contextUpdated(); - } - - /** - * Action handler called when the Date filter is changed by the user - */ - public void dateFilterChanged(ActionEvent event) - { - UIModeList filterComponent = (UIModeList)event.getComponent(); - property.setDateFilter(filterComponent.getValue().toString()); - contextUpdated(); - property.setShowItems(true); - } - - /** - * Action handler called when the User filter is changed by the user - */ - public void userFilterChanged(ActionEvent event) - { - UIModeList filterComponent = (UIModeList)event.getComponent(); - property.setUserFilter(filterComponent.getValue().toString()); - contextUpdated(); - property.setShowItems(true); - } - - - // ------------------------------------------------------------------------------ - // Private helpers - - /** - * @return the archive store root node ref - */ - private NodeRef getArchiveRootRef() - { - if (property.getArchiveRootRef() == null) - { - property.setArchiveRootRef(property.getNodeArchiveService().getStoreArchiveNode(Repository.getStoreRef())); - } - return property.getArchiveRootRef(); - } - - /** - * @return the search query to use when displaying the list of deleted items - */ - @SuppressWarnings("deprecation") - private String buildSearchQuery() - { - String query; - if (property.getSearchText() == null || property.getSearchText().length() == 0) - { - // search for ALL items in the archive store - query = String.format(SEARCH_ALL, property.getArchiveRootRef(), ContentModel.ASPECT_ARCHIVED); - } - else - { - // search by name in the archive store - String safeText = SearchLanguageConversion.escapeLuceneQuery(property.getSearchText()); - if (safeText.indexOf(' ') == -1) - { - if (property.isFullTextSearch()) - { - query = String.format(SEARCH_TEXT, property.getArchiveRootRef(), ContentModel.ASPECT_ARCHIVED, safeText); - } - else - { - query = String.format(SEARCH_NAME, property.getArchiveRootRef(), ContentModel.ASPECT_ARCHIVED, safeText, safeText); - } - } - else - { - if (property.isFullTextSearch()) - { - query = String.format(SEARCH_TEXT_QUOTED, property.getArchiveRootRef(), ContentModel.ASPECT_ARCHIVED, safeText); - } - else - { - query = String.format(SEARCH_NAME_QUOTED, property.getArchiveRootRef(), ContentModel.ASPECT_ARCHIVED, safeText); - } - } - } - - // append user search clause - String username = null; - if (isAdminUser() == false) - { - // prefix the current username - username = Application.getCurrentUser(FacesContext.getCurrentInstance()).getUserName(); - } - else if (FILTER_USER_USER.equals(property.getUserFilter())) - { - // append the entered user if admin has requested a search - username = property.getUserSearchText(); - } - if (username != null && username.length() != 0) - { - query = String.format(SEARCH_USERPREFIX, username) + query; - } - - // append date search clause - if (FILTER_DATE_ALL.equals(property.getDateFilter()) == false) - { - Date toDate = new Date(); - Date fromDate = null; - if (FILTER_DATE_TODAY.equals(property.getDateFilter())) - { - fromDate = new Date(toDate.getYear(), toDate.getMonth(), toDate.getDate(), 0, 0, 0); - } - else if (FILTER_DATE_WEEK.equals(property.getDateFilter())) - { - fromDate = new Date(toDate.getTime() - (1000L*60L*60L*24L*7L)); - } - else if (FILTER_DATE_MONTH.equals(property.getDateFilter())) - { - fromDate = new Date(toDate.getTime() - (1000L*60L*60L*24L*30L)); - } - if (fromDate != null) - { - SimpleDateFormat df = CachingDateFormat.getDateFormat(); - String strFromDate = SearchLanguageConversion.escapeLuceneQuery(df.format(fromDate)); - String strToDate = SearchLanguageConversion.escapeLuceneQuery(df.format(toDate)); - StringBuilder buf = new StringBuilder(128); - buf.append("@").append(DATE_ATTR) - .append(":").append("[").append(strFromDate) - .append(" TO ").append(strToDate).append("] AND "); - - query = buf.toString() + query; - } - } - - return query; - } - - /** - * Save the detail of the items that were successfully or unsuccessfully restored - * - * @param reports The List of RestoreNodeReport objects to walk for results - */ - protected void saveReportDetail(List reports) - { - // store the results ready for the next dialog page - int failureItemsCount = 0; - property.setSuccessItems(new ArrayList(reports.size())); - property.setFailureItems(new ArrayList(reports.size())); - for (RestoreNodeReport report : reports) - { - if (RestoreStatus.SUCCESS == report.getStatus()) - { - Node node = new Node(report.getRestoredNodeRef()); - node.getProperties().put(PROP_RECOVERSTATUS, report.getStatus()); - property.getSuccessItems().add(node); - } - else - { - if (failureItemsCount < MAX_FAILURE_REPORTS) - { - Node node = new Node(report.getArchivedNodeRef()); - node.getProperties().put(PROP_RECOVERSTATUS, report.getStatus()); - node.getProperties().put(PROP_RECOVERERRORMESSAGE, report.getCause().getMessage()); - property.getFailureItems().add(node); - failureItemsCount++; - } - } - } - } - - /** - * Build an HTML table of the items that are to be or have been recovered. - * - * @param items List of Node objects to display in the table - * @param cssClass CSS style to apply to the table - * @param report Set true to report the reason for any failure. This flag requires that the Node - * object has a pseudo property "recoverstatus" containing the RestoreStatus. - * @param archivedPath Set true to show the path from the 'sys:archivedOriginalParentAssoc' property, - * else the current Node Path will be used. - * - * - * @return HTML table of node info - */ - private String buildItemsTable(List items, String cssClass, boolean report, boolean archivedPath) - { - FacesContext fc = FacesContext.getCurrentInstance(); - String contextPath = fc.getExternalContext().getRequestContextPath(); - - StringBuilder buf = new StringBuilder(1024); - - // outer table - buf.append(""); - // title row - buf.append(""); - if (report == true) - { - buf.append(""); - } - else - { - buf.append(""); - } - buf.append(""); - for (Node node : items) - { - // listed item rows - buf.append(""); - - if (report) - { - buf.append(""); - } - else - { - buf.append(""); - } - - buf.append(""); - } - // end table - buf.append("
"); - buf.append(Application.getMessage(fc, MSG_NAME)); - buf.append(""); - buf.append(Application.getMessage(fc, MSG_RECOVERY_REASON)); - buf.append(""); - buf.append(Application.getMessage(fc, MSG_LOCATION)); - buf.append("
"); - String img; - if (getDictionaryService().isSubClass(node.getType(), ContentModel.TYPE_FOLDER)) - { - String icon = (String)node.getProperties().get("app:icon"); - img = "/images/icons/" + (icon != null ? icon + "-16.gif" : BrowseBean.SPACE_SMALL_DEFAULT + ".gif"); - } - else - { - img = FileTypeImageUtils.getFileTypeImage(node.getName(), true); - } - buf.append(""); - buf.append(""); - buf.append(Utils.encode(node.getName())); - buf.append(""); - String msg; - RestoreStatus status = (RestoreStatus) node.getProperties().get(PROP_RECOVERSTATUS); - String message = (String) node.getProperties().get(PROP_RECOVERERRORMESSAGE); - switch (status) - { - case FAILURE_INVALID_PARENT: - msg = MSG_RECOVERED_ITEM_PARENT_S; - break; - - case FAILURE_PERMISSION: - msg = MSG_RECOVERED_ITEM_PERMISSION_S; - break; - - case FAILURE_INTEGRITY: - msg = MSG_RECOVERED_ITEM_INTEGRITY_S; - break; - - case FAILURE_DUPLICATE_CHILD_NODE_NAME: - msg = MSG_RECOVERED_ITEM_DUPLICATE_S; - break; - - default: - msg = MSG_RECOVERED_ITEM_FAILURE_S; - break; - } - buf.append(Application.getMessage(fc, msg)); - buf.append(": "); - buf.append(message); - buf.append(""); - if (archivedPath) - { - ChildAssociationRef childRef = (ChildAssociationRef)node.getProperties().get(ContentModel.PROP_ARCHIVED_ORIGINAL_PARENT_ASSOC); - if (getNodeService().exists(childRef.getParentRef())) - { - buf.append(Utils.encode(Repository.getNamePath(getNodeService(), getNodeService().getPath(childRef.getParentRef()), null, "/", null))); - } - } - else - { - buf.append(Utils.encode(Repository.getNamePath(getNodeService(), getNodeService().getPath(node.getNodeRef()), null, "/", null))); - } - buf.append("
"); - - return buf.toString(); - } - - private boolean isAdminUser() - { - return Application.getCurrentUser(FacesContext.getCurrentInstance()).isAdmin(); - } - - - // ------------------------------------------------------------------------------ - // IContextListener implementation - - /** - * @see org.alfresco.web.app.context.IContextListener#contextUpdated() - */ - public void contextUpdated() - { - if (property.getItemsRichList() != null) - { - property.getItemsRichList().setValue(null); - } - property.setShowItems(false); - } - - /** - * @see org.alfresco.web.app.context.IContextListener#areaChanged() - */ - public void areaChanged() - { - // nothing to do - } - - /** - * @see org.alfresco.web.app.context.IContextListener#spaceChanged() - */ - public void spaceChanged() - { - // nothing to do - } - - @Override - public String cancel() - { - close(); - return super.cancel(); - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } - -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanDialogProperty.java b/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanDialogProperty.java deleted file mode 100644 index be8279e368..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanDialogProperty.java +++ /dev/null @@ -1,315 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.trashcan; - -import java.io.Serializable; -import java.util.Collections; -import java.util.List; - -import javax.faces.context.FacesContext; - -import org.alfresco.repo.node.archive.NodeArchiveService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.ui.common.component.data.UIRichList; - -public class TrashcanDialogProperty implements Serializable -{ - private static final long serialVersionUID = -8007742798807270570L; - - private static final String FILTER_DATE_ALL = "all"; - private static final String FILTER_USER_ALL = "all"; - - /** NodeArchiveService bean reference */ - transient private NodeArchiveService nodeArchiveService; - - /** Component reference for Deleted Items RichList control */ - protected UIRichList itemsRichList; - - /** Search text */ - private String searchText = null; - - /** We show an empty list until a Search or Show All is executed */ - private boolean showItems = false; - - private boolean fullTextSearch = false; - - /** Currently listed items */ - private List listedItems = Collections. emptyList(); - - private List successItems = Collections. emptyList(); - - private List failureItems = Collections. emptyList(); - - /** Current action context Node */ - private Node actionNode; - - /** Root node to the spaces store archive store */ - private NodeRef archiveRootRef = null; - - /** Alternative destination for recovered items */ - private NodeRef destination = null; - - /** Date filter selection */ - private String dateFilter = FILTER_DATE_ALL; - - /** User filter selection */ - private String userFilter = FILTER_USER_ALL; - - /** User filter search box text */ - private String userSearchText = null; - - private boolean inProgress = false; - - /** - * @param nodeArchiveService The nodeArchiveService to set. - */ - public void setNodeArchiveService(NodeArchiveService nodeArchiveService) - { - this.nodeArchiveService = nodeArchiveService; - } - - /** - * @return Returns the itemsRichList. - */ - public UIRichList getItemsRichList() - { - return this.itemsRichList; - } - - /** - * @param itemsRichList The itemsRichList to set. - */ - public void setItemsRichList(UIRichList itemsRichList) - { - this.itemsRichList = itemsRichList; - } - - /** - * @return Returns the searchText. - */ - public String getSearchText() - { - return this.searchText; - } - - /** - * @param searchText The searchText to set. - */ - public void setSearchText(String searchText) - { - this.searchText = searchText; - } - - /** - * @return Returns the alternative destination to use if recovery fails. - */ - public NodeRef getDestination() - { - return this.destination; - } - - /** - * @param destination The alternative destination to use if recovery fails. - */ - public void setDestination(NodeRef destination) - { - this.destination = destination; - } - - /** - * @return Returns the dateFilter. - */ - public String getDateFilter() - { - return this.dateFilter; - } - - /** - * @param dateFilter The dateFilter to set. - */ - public void setDateFilter(String dateFilter) - { - this.dateFilter = dateFilter; - } - - /** - * @return Returns the userFilter. - */ - public String getUserFilter() - { - return this.userFilter; - } - - /** - * @param userFilter The userFilter to set. - */ - public void setUserFilter(String userFilter) - { - this.userFilter = userFilter; - } - - /** - * @return Returns the userSearchText. - */ - public String getUserSearchText() - { - return this.userSearchText; - } - - /** - * @param userSearchText The userSearchText to set. - */ - public void setUserSearchText(String userSearchText) - { - this.userSearchText = userSearchText; - } - - /** - * @return Returns the listed items. - */ - public List getListedItems() - { - return this.listedItems; - } - - /** - * @param listedItems The listed items to set. - */ - public void setListedItems(List listedItems) - { - this.listedItems = listedItems; - } - - /** - * @return count of the items that failed to recover - */ - public int getFailureItemsCount() - { - return this.failureItems.size(); - } - - /** - * @param node The item context for the current action - */ - public void setItem(Node node) - { - this.actionNode = node; - } - - /** - * @return the item context for the current action - */ - public Node getItem() - { - return this.actionNode; - } - - public boolean isShowItems() - { - return showItems; - } - - public void setShowItems(boolean showItems) - { - this.showItems = showItems; - } - - public boolean isFullTextSearch() - { - return fullTextSearch; - } - - public void setFullTextSearch(boolean fullTextSearch) - { - this.fullTextSearch = fullTextSearch; - } - - public List getSuccessItems() - { - return successItems; - } - - public void setSuccessItems(List successItems) - { - this.successItems = successItems; - } - - public List getFailureItems() - { - return failureItems; - } - - public void setFailureItems(List failureItems) - { - this.failureItems = failureItems; - } - - public Node getActionNode() - { - return actionNode; - } - - public void setActionNode(Node actionNode) - { - this.actionNode = actionNode; - } - - public NodeRef getArchiveRootRef() - { - return archiveRootRef; - } - - public void setArchiveRootRef(NodeRef archiveRootRef) - { - this.archiveRootRef = archiveRootRef; - } - - public boolean isInProgress() - { - return inProgress; - } - - public void setInProgress(boolean inProgress) - { - this.inProgress = inProgress; - } - - /** - *@return nodeArchiveService - */ - public NodeArchiveService getNodeArchiveService() - { - //check for null for cluster environment - if (nodeArchiveService == null) - { - nodeArchiveService = (NodeArchiveService) FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), "nodeArchiveService"); - } - return nodeArchiveService; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanItemDetailsDialog.java b/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanItemDetailsDialog.java deleted file mode 100644 index c814b32425..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanItemDetailsDialog.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.trashcan; - -import javax.faces.context.FacesContext; - -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; - -public class TrashcanItemDetailsDialog extends TrashcanDialog -{ - private static final long serialVersionUID = 1767515883530860417L; - - private static final String MSG_DETAILS_OF = "details_of"; - private static final String MSG_CLOSE = "close"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - transient private PermissionService permissionService; - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_DETAILS_OF) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) + - property.getItem().getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } - - @Override - public Object getActionsContext() - { - return getItem(); - } - - public Node getItem() - { - return property.getItem(); - } - - public void setPermissionService(PermissionService permissionService) - { - this.permissionService = permissionService; - } - - /** - *@return permissionService - */ - protected PermissionService getPermissionService() - { - //check for null for cluster environment - if (permissionService == null) - { - permissionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPermissionService(); - } - return permissionService; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanRecoverItemDialog.java b/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanRecoverItemDialog.java deleted file mode 100644 index 29c0126d15..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanRecoverItemDialog.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.trashcan; - -import java.text.MessageFormat; - -import javax.faces.application.FacesMessage; -import javax.faces.context.FacesContext; - -import org.alfresco.repo.node.archive.RestoreNodeReport; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.ui.common.ReportedException; - -public class TrashcanRecoverItemDialog extends TrashcanDialog -{ - private static final long serialVersionUID = -8237457079397611071L; - - private static final String RICHLIST_ID = "trashcan-list"; - private static final String RICHLIST_MSG_ID = "trashcan" + ':' + RICHLIST_ID; - private static final String MSG_RECOVERED_ITEM_SUCCESS = "recovered_item_success"; - private static final String MSG_RECOVERED_ITEM_DUPLICATE = "recovered_item_duplicate"; - private static final String MSG_RECOVERED_ITEM_INTEGRITY = "recovered_item_integrity"; - private static final String MSG_RECOVERED_ITEM_PERMISSION = "recovered_item_permission"; - private static final String MSG_RECOVERED_ITEM_PARENT = "recovered_item_parent"; - private static final String MSG_RECOVERED_ITEM_FAILURE = "recovered_item_failure"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - private static final String MSG_RECOVER_ITEM = "recover_item"; - private static final String MSG_NO = "no"; - private static final String MSG_YES = "yes"; - - private String recoverItem(FacesContext context, String outcome) - { - Node item = property.getItem(); - if (item != null) - { - FacesContext fc = context; - try - { - String msg; - FacesMessage errorfacesMsg = null; - - // restore the node - the user may have requested a restore to a - // different parent - RestoreNodeReport report; - if (property.getDestination() == null) - { - report = property.getNodeArchiveService().restoreArchivedNode(item.getNodeRef()); - } - else - { - report = property.getNodeArchiveService().restoreArchivedNode(item.getNodeRef(), property.getDestination(), null, null); - } - switch (report.getStatus()) - { - case SUCCESS: - msg = MessageFormat.format(Application.getMessage(fc, MSG_RECOVERED_ITEM_SUCCESS), item.getName()); - FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg); - fc.addMessage(RICHLIST_MSG_ID, facesMsg); - - break; - - case FAILURE_INVALID_PARENT: - msg = MessageFormat.format(Application.getMessage(fc, MSG_RECOVERED_ITEM_PARENT), item.getName()); - errorfacesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg); - break; - - case FAILURE_PERMISSION: - msg = MessageFormat.format(Application.getMessage(fc, MSG_RECOVERED_ITEM_PERMISSION), item.getName()); - errorfacesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg); - break; - - case FAILURE_INTEGRITY: - msg = MessageFormat.format(Application.getMessage(fc, MSG_RECOVERED_ITEM_INTEGRITY), item.getName()); - errorfacesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg); - break; - - case FAILURE_DUPLICATE_CHILD_NODE_NAME: - msg = MessageFormat.format(Application.getMessage(fc, MSG_RECOVERED_ITEM_DUPLICATE), item.getName()); - errorfacesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg); - break; - - default: - String reason = report.getCause().getMessage(); - msg = MessageFormat.format(Application.getMessage(fc, MSG_RECOVERED_ITEM_FAILURE), item.getName(), reason); - errorfacesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg); - break; - } - - // report the failure if one occured we stay on the current - // screen - if (errorfacesMsg != null) - { - fc.addMessage(null, errorfacesMsg); - } - } - catch (Throwable err) - { - // most exceptions will be caught and returned as - // RestoreNodeReport objects by the service - String reason = err.getMessage(); - String msg = MessageFormat.format(Application.getMessage(fc, MSG_RECOVERED_ITEM_FAILURE), item.getName(), reason); - FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg); - fc.addMessage(null, facesMsg); - ReportedException.throwIfNecessary(err); - } - } - - return outcome; - } - - @Override - protected String getDefaultFinishOutcome() - { - return "dialog:close[2]"; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return recoverItem(context, outcome); - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_RECOVER_ITEM) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) - + property.getItem().getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_NO); - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_YES); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanRecoverListedItemsDialog.java b/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanRecoverListedItemsDialog.java deleted file mode 100644 index b1367c55ae..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanRecoverListedItemsDialog.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.trashcan; - -import java.util.ArrayList; -import java.util.List; - -import javax.faces.context.FacesContext; - -import org.alfresco.repo.node.archive.RestoreNodeReport; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; - -public class TrashcanRecoverListedItemsDialog extends TrashcanDialog -{ - private static final long serialVersionUID = 5500454626559426051L; - - private static final String OUTCOME_RECOVERY_REPORT = "dialog:recoveryReport"; - private static final String MSG_NO = "no"; - private static final String MSG_YES = "yes"; - - private String recoverListedItems(FacesContext context, String outcome) - { - if (property.isInProgress()) - return null; - - property.setInProgress(true); - - try - { - - // restore the nodes - the user may have requested a restore to a - // different parent - List nodeRefs = new ArrayList(property.getListedItems().size()); - for (Node node : property.getListedItems()) - { - nodeRefs.add(node.getNodeRef()); - } - List reports; - if (property.getDestination() == null) - { - reports = property.getNodeArchiveService().restoreArchivedNodes(nodeRefs); - } - else - { - reports = property.getNodeArchiveService().restoreArchivedNodes(nodeRefs, property.getDestination(), null, null); - } - - saveReportDetail(reports); - - } - finally - { - property.setInProgress(false); - } - - return OUTCOME_RECOVERY_REPORT; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - - return recoverListedItems(context, outcome); - - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_NO); - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_YES); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanRecoveryReportDialog.java b/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanRecoveryReportDialog.java deleted file mode 100644 index 0b8748cd1e..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/trashcan/TrashcanRecoveryReportDialog.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.trashcan; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.Application; - -public class TrashcanRecoveryReportDialog extends TrashcanDialog -{ - - private static final long serialVersionUID = -3381444990908748991L; - - private final static String MSG_CLOSE = "close"; - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return outcome; - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } - - @Override - protected String getDefaultCancelOutcome() - { - return "dialog:close[2]"; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/users/ChangeMyPasswordDialog.java b/war/src/main/java/org/alfresco/web/bean/users/ChangeMyPasswordDialog.java deleted file mode 100644 index 9fe86a0140..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/ChangeMyPasswordDialog.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.web.app.Application; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; - -public class ChangeMyPasswordDialog extends UsersDialog -{ - - private static final long serialVersionUID = 1965846039555088108L; - - private static final String MSG_FINISH_BUTTON = "finish_button"; - private static final String MSG_ERROR_INCORRECT_OLD_PASSWORD = "error_incorrect_old_password"; - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - String result = changeMyPasswordOK(outcome, context); - if (result == null) - { - isFinished = false; - } - return result; - } - - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_FINISH_BUTTON); - } - - public boolean getFinishButtonDisabled() - { - return false; - } - - /** - * Action handler called for OK button press on Change My Password screen For this screen the user is required to enter their old password - effectively login. - */ - public String changeMyPasswordOK(String newOutcome, FacesContext newContext) - { - String outcome = newOutcome; - - if (properties.getPassword() != null && properties.getConfirm() != null && properties.getPassword().equals(properties.getConfirm())) - { - try - { - String userName = (String) properties.getPerson().getProperties().get(ContentModel.PROP_USERNAME); - properties.getAuthenticationService().updateAuthentication(userName, properties.getOldPassword().toCharArray(), properties.getPassword().toCharArray()); - } - catch (Exception e) - { - outcome = null; - Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), - MSG_ERROR_INCORRECT_OLD_PASSWORD)); - ReportedException.throwIfNecessary(e); - } - } - else - { - outcome = null; - Utils.addErrorMessage(Application.getMessage(newContext, ERROR_PASSWORD_MATCH)); - } - - return outcome; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/users/ChangePasswordDialog.java b/war/src/main/java/org/alfresco/web/bean/users/ChangePasswordDialog.java deleted file mode 100644 index 32430afbc3..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/ChangePasswordDialog.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import java.text.MessageFormat; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; - -public class ChangePasswordDialog extends UsersDialog -{ - - private static final long serialVersionUID = -1570967895811499123L; - - private static final String MSG_FINISH_BUTTON = "finish_button"; - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - String result = changePasswordOK(outcome, context); - if (result == null) - { - isFinished = false; - } - return result; - } - - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_FINISH_BUTTON); - } - - public boolean getFinishButtonDisabled() - { - return false; - } - - /** - * Action handler called for OK button press on Change Password screen - */ - public String changePasswordOK(String newOutcome, FacesContext newContext) - { - String outcome = newOutcome; - - if (properties.getPassword() != null && properties.getConfirm() != null && properties.getPassword().equals(properties.getConfirm())) - { - try - { - String userName = (String) properties.getPerson().getProperties().get(ContentModel.PROP_USERNAME); - properties.getAuthenticationService().setAuthentication(userName, properties.getPassword().toCharArray()); - } - catch (Exception e) - { - outcome = null; - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(newContext, Repository.ERROR_GENERIC), e.getMessage()), e); - ReportedException.throwIfNecessary(e); - } - } - else - { - outcome = null; - Utils.addErrorMessage(Application.getMessage(newContext, ERROR_PASSWORD_MATCH)); - } - - return outcome; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/users/ContentUsersBean.java b/war/src/main/java/org/alfresco/web/bean/users/ContentUsersBean.java deleted file mode 100644 index b7a41c701e..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/ContentUsersBean.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import java.text.MessageFormat; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; - -/** - * Concrete implementation providing access to users of the current content/document. - * - * @author gavinc - */ -public class ContentUsersBean extends UserMembersBean -{ - private static final long serialVersionUID = 5206400236997654181L; - - private final static String MSG_MANAGE_CONTENT_USERS = "manage_content_users"; - private final static String MSG_CONTENT_OWNER = "content_owner"; - private final static String MSG_CLOSE= "close"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - /** - * @return The space to work against - */ - public Node getNode() - { - return this.browseBean.getDocument(); - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - @Override - public Object getActionsContext() - { - return getNode(); - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_MANAGE_CONTENT_USERS) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) - + browseBean.getDocument().getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - @Override - public String getContainerSubTitle() - { - String pattern = Application.getMessage(FacesContext.getCurrentInstance(), MSG_CONTENT_OWNER); - return MessageFormat.format(pattern, getOwner()); - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/users/CreateUserWizard.java b/war/src/main/java/org/alfresco/web/bean/users/CreateUserWizard.java deleted file mode 100644 index c44657e9c9..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/CreateUserWizard.java +++ /dev/null @@ -1,1007 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.ResourceBundle; -import java.util.regex.Pattern; - -import javax.faces.application.FacesMessage; -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.faces.validator.ValidatorException; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.security.person.PersonServiceImpl; -import org.alfresco.repo.tenant.TenantDomainMismatchException; -import org.alfresco.repo.tenant.TenantService; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.security.MutableAuthenticationService; -import org.alfresco.service.cmr.security.OwnableService; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.cmr.security.PersonService; -import org.alfresco.service.cmr.usage.ContentUsageService; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.util.Pair; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.LoginBean; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.spaces.CreateSpaceWizard; -import org.alfresco.web.bean.wizard.BaseWizardBean; -import org.alfresco.web.config.ClientConfigElement; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.validator.routines.EmailValidator; - -/** - * @author Kevin Roast - */ -public class CreateUserWizard extends BaseWizardBean -{ - private static final long serialVersionUID = 8008464794715380019L; - - private static Log logger = LogFactory.getLog(BaseWizardBean.class); - protected static final String ERROR = "error_person"; - protected static final String ERROR_DOMAIN_MISMATCH = "error_domain_mismatch"; - - private static final String MSG_ERROR_NEWUSER_HOME_SPACE = "error_newuser_home_space"; - private static final String MSG_ERROR_MAIL_NOT_VALID = "email_format_is_not_valid"; - - protected static final String QUOTA_UNITS_KB = "kilobyte"; - protected static final String QUOTA_UNITS_MB = "megabyte"; - protected static final String QUOTA_UNITS_GB = "gigabyte"; - - /** form variables */ - protected String firstName = null; - protected String lastName = null; - protected String userName = null; - protected String password = null; - protected String confirm = null; - protected String email = null; - protected String companyId = null; - protected String homeSpaceName = ""; - protected NodeRef homeSpaceLocation = null; - protected String presenceProvider = null; - protected String presenceUsername = null; - protected String organisation = null; - protected String jobtitle = null; - protected String location = null; - - protected Long sizeQuota = null; // null is also equivalent to -1 (ie. no quota limit set) - protected String sizeQuotaUnits = null; - - /** AuthenticationService bean reference */ - transient private MutableAuthenticationService authenticationService; - - /** PersonService bean reference */ - transient private PersonService personService; - - /** TenantService bean reference */ - transient private TenantService tenantService; - - /** PermissionService bean reference */ - transient private PermissionService permissionService; - - /** OwnableService bean reference */ - transient private OwnableService ownableService; - - /** ContentUsageService bean reference */ - transient private ContentUsageService contentUsageService; - - /** ref to the company home space folder */ - private NodeRef companyHomeSpaceRef = null; - - /** ref to the default home location */ - private NodeRef defaultHomeSpaceRef; - - /** - * @param authenticationService The AuthenticationService to set. - */ - public void setAuthenticationService(MutableAuthenticationService authenticationService) - { - this.authenticationService = authenticationService; - } - - /** - * @return authenticationService - */ - private MutableAuthenticationService getAuthenticationService() - { - if (authenticationService == null) - { - authenticationService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getAuthenticationService(); - } - return authenticationService; - } - - /** - * @param personService The person service. - */ - public void setPersonService(PersonService personService) - { - this.personService = personService; - } - - /** - * @return personService - */ - private PersonService getPersonService() - { - if (personService == null) - { - personService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPersonService(); - } - return personService; - } - - /** - * @param tenantService The tenantService to set. - */ - public void setTenantService(TenantService tenantService) - { - this.tenantService = tenantService; - } - - /** - * @return tenantService - */ - private TenantService getTenantService() - { - if(tenantService == null) - { - tenantService = (TenantService) FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), "tenantService"); - } - return tenantService; - } - - /** - * @param permissionService The PermissionService to set. - */ - public void setPermissionService(PermissionService permissionService) - { - this.permissionService = permissionService; - } - - /** - * @return permissionService - */ - private PermissionService getPermissionService() - { - if (permissionService == null) - { - permissionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPermissionService(); - } - return permissionService; - } - - /** - * @param ownableService The ownableService to set. - */ - public void setOwnableService(OwnableService ownableService) - { - this.ownableService = ownableService; - } - - /** - * @return ownableService - */ - private OwnableService getOwnableService() - { - if (ownableService == null) - { - ownableService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getOwnableService(); - } - return ownableService; - } - - /** - * @param contentUsageService The contentUsageService to set. - */ - public void setContentUsageService(ContentUsageService contentUsageService) - { - this.contentUsageService = contentUsageService; - } - - /** - * @return contentUsageService - */ - private ContentUsageService getContentUsageService() - { - if (contentUsageService == null) - { - contentUsageService = (ContentUsageService) FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), "ContentUsageService"); - } - return contentUsageService; - } - - /** - * Initialises the wizard - */ - @Override - public void init(Map params) - { - super.init(params); - - // reset all variables - this.firstName = ""; - this.lastName = ""; - this.userName = ""; - this.password = ""; - this.confirm = ""; - this.email = ""; - this.companyId = ""; - this.homeSpaceName = ""; - this.homeSpaceLocation = getDefaultHomeSpace(); - this.presenceProvider = ""; - this.presenceUsername = ""; - this.organisation = ""; - this.jobtitle = ""; - this.location = ""; - - this.sizeQuota = null; - this.sizeQuotaUnits = ""; - } - - /** - * @return Returns the summary data for the wizard. - */ - public String getSummary() - { - ResourceBundle bundle = Application.getBundle(FacesContext.getCurrentInstance()); - - String homeSpaceLabel = this.homeSpaceName; - if (this.homeSpaceName.length() == 0 && this.homeSpaceLocation != null) - { - homeSpaceLabel = Repository.getNameForNode(this.getNodeService(), this.homeSpaceLocation); - } - - String quotaLabel = ""; - if (this.sizeQuota != null && this.sizeQuota != -1L) - { - quotaLabel = Long.toString(this.sizeQuota) + bundle.getString(this.sizeQuotaUnits); - } - - String presenceLabel = ""; - if (this.presenceProvider != null && this.presenceProvider.length() != 0) - { - presenceLabel = this.presenceUsername + " (" + presenceProvider + ")"; - } - - return buildSummary( - new String[] { - bundle.getString("name"), bundle.getString("username"), - bundle.getString("password"), bundle.getString("homespace"), - bundle.getString("email"), bundle.getString("user_organization"), - bundle.getString("user_jobtitle"), bundle.getString("user_location"), - bundle.getString("presence_username"), bundle.getString("quota")}, - new String[] { - Utils.encode(this.firstName + " " + this.lastName), Utils.encode(this.userName), - "********", Utils.encode(homeSpaceLabel), - Utils.encode(this.email), Utils.encode(this.organisation), - Utils.encode(this.jobtitle), Utils.encode(this.location), - Utils.encode(presenceLabel), quotaLabel}); - } - - /** - * Init the users screen - */ - public void setupUsers(ActionEvent event) - { - invalidateUserList(); - } - - /** - * @return Returns the companyId. - */ - public String getCompanyId() - { - return this.companyId; - } - - /** - * @param companyId The companyId to set. - */ - public void setCompanyId(String companyId) - { - this.companyId = companyId; - } - - /** - * @return Returns the presenceProvider. - */ - public String getPresenceProvider() - { - return this.presenceProvider; - } - - /** - * @param presenceProvider - * The presenceProvider to set. - */ - public void setPresenceProvider(String presenceProvider) - { - this.presenceProvider = presenceProvider; - } - - /** - * @return Returns the presenceUsername. - */ - public String getPresenceUsername() - { - return this.presenceUsername; - } - - /** - * @param presenceUsername - * The presenceUsername to set. - */ - public void setPresenceUsername(String presenceUsername) - { - this.presenceUsername = presenceUsername; - } - - /** - * @return Returns the email. - */ - public String getEmail() - { - return this.email; - } - - /** - * @param email The email to set. - */ - public void setEmail(String email) - { - this.email = email; - } - - /** - * @return Returns the firstName. - */ - public String getFirstName() - { - return this.firstName; - } - - /** - * @param firstName The firstName to set. - */ - public void setFirstName(String firstName) - { - this.firstName = firstName; - } - - /** - * @return Returns the homeSpaceLocation. - */ - public NodeRef getHomeSpaceLocation() - { - return this.homeSpaceLocation; - } - - /** - * @param homeSpaceLocation The homeSpaceLocation to set. - */ - public void setHomeSpaceLocation(NodeRef homeSpaceLocation) - { - this.homeSpaceLocation = homeSpaceLocation; - } - - /** - * @return Returns the homeSpaceName. - */ - public String getHomeSpaceName() - { - return this.homeSpaceName; - } - - /** - * @param homeSpaceName The homeSpaceName to set. - */ - public void setHomeSpaceName(String homeSpaceName) - { - this.homeSpaceName = homeSpaceName; - } - - /** - * @return Returns the lastName. - */ - public String getLastName() - { - return this.lastName; - } - - /** - * @param lastName The lastName to set. - */ - public void setLastName(String lastName) - { - this.lastName = lastName; - } - - /** - * @return Returns the userName. - */ - public String getUserName() - { - return this.userName; - } - - /** - * @param userName The userName to set. - */ - public void setUserName(String userName) - { - this.userName = (userName != null ? userName.trim() : null); - } - - /** - * @return Returns the password. - */ - public String getPassword() - { - return this.password; - } - - /** - * @param password The password to set. - */ - public void setPassword(String password) - { - this.password = password; - } - - /** - * @return Returns the confirm password. - */ - public String getConfirm() - { - return this.confirm; - } - - /** - * @param confirm The confirm password to set. - */ - public void setConfirm(String confirm) - { - this.confirm = confirm; - } - - /** - * @return the jobtitle - */ - public String getJobtitle() - { - return this.jobtitle; - } - - /** - * @param jobtitle the jobtitle to set - */ - public void setJobtitle(String jobtitle) - { - this.jobtitle = jobtitle; - } - - /** - * @return the location - */ - public String getLocation() - { - return this.location; - } - - /** - * @param location the location to set - */ - public void setLocation(String location) - { - this.location = location; - } - - /** - * @return the organisation - */ - public String getOrganization() - { - return this.organisation; - } - - /** - * @param organisation the organisation to set - */ - public void setOrganization(String organisation) - { - this.organisation = organisation; - } - - public Long getSizeQuota() - { - return sizeQuota; - } - - public void setSizeQuota(Long sizeQuota) - { - this.sizeQuota = sizeQuota; - } - - public String getSizeQuotaUnits() - { - return sizeQuotaUnits; - } - - public void setSizeQuotaUnits(String sizeQuotaUnits) - { - this.sizeQuotaUnits = sizeQuotaUnits; - } - - // ------------------------------------------------------------------------------ - // Validator methods - - /** - * Validate password field data is acceptable - * - * @deprecated Method is never used - */ - public void validatePassword(FacesContext context, UIComponent component, Object value) throws ValidatorException - { - int minPasswordLength = Application.getClientConfig(context).getMinPasswordLength(); - int maxPasswordLength = Application.getClientConfig(context).getMaxPasswordLength(); - - String pass = (String)value; - if (pass.length() < minPasswordLength || pass.length() > maxPasswordLength) - { - String err = MessageFormat.format(Application.getMessage(context, LoginBean.MSG_PASSWORD_LENGTH), - new Object[]{minPasswordLength, maxPasswordLength}); - throw new ValidatorException(new FacesMessage(err)); - } - } - - /** - * Validate Username field data is acceptable - */ - public void validateUsername(FacesContext context, UIComponent component, Object value) throws ValidatorException - { - int minUsernameLength = Application.getClientConfig(context).getMinUsernameLength(); - - String name = ((String)value).trim(); - if (name.length() < minUsernameLength || name.length() > 256) - { - String err = MessageFormat.format(Application.getMessage(context, LoginBean.MSG_USERNAME_LENGTH), - new Object[]{minUsernameLength, 256}); - throw new ValidatorException(new FacesMessage(err)); - } - if (name.indexOf('"') != -1 || name.indexOf('\\') != -1) - { - String err = MessageFormat.format(Application.getMessage(context, LoginBean.MSG_USER_ERR), - new Object[]{"\", \\"}); - throw new ValidatorException(new FacesMessage(err)); - } - - try - { - name = PersonServiceImpl.updateUsernameForTenancy( - name, getTenantService() - ); - } - catch(TenantDomainMismatchException e) - { - String err = MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), - ERROR_DOMAIN_MISMATCH), e.getTenantA(), e.getTenantB()); - throw new ValidatorException(new FacesMessage(err)); - } - } - - /** - * Validate Email field data is acceptable - * - * @param context FacesContext - * @param component UIComponent - * @param value Object - * @throws ValidatorException - */ - public void validateEmail(FacesContext context, UIComponent component, Object value) throws ValidatorException - { - String emailRegExp = Application.getClientConfig(context).getEmailRegExp(); - Pattern pattern = Pattern.compile(emailRegExp, Pattern.CASE_INSENSITIVE); - if (!pattern.matcher((CharSequence) value).matches()) - { - String err = Application.getMessage(context, MSG_ERROR_MAIL_NOT_VALID); - throw new ValidatorException(new FacesMessage(err)); - } - } - - // ------------------------------------------------------------------------------ - // Helper methods - - /** - * Helper to return the company home space - * - * @return company home space NodeRef - */ - protected NodeRef getCompanyHomeSpace() - { - if (this.companyHomeSpaceRef == null) - { - String companyXPath = Application.getRootPath(FacesContext.getCurrentInstance()); - - NodeRef rootNodeRef = this.getNodeService().getRootNode(Repository.getStoreRef()); - List nodes = this.getSearchService().selectNodes(rootNodeRef, companyXPath, null, this.getNamespaceService(), false); - - if (nodes.size() == 0) - { - throw new IllegalStateException("Unable to find company home space path: " + companyXPath); - } - - this.companyHomeSpaceRef = nodes.get(0); - } - - return this.companyHomeSpaceRef; - } - - protected NodeRef getDefaultHomeSpace() - { - if ((this.defaultHomeSpaceRef == null) || !getNodeService().exists(this.defaultHomeSpaceRef)) - { - String defaultHomeSpacePath = Application.getClientConfig(FacesContext.getCurrentInstance()).getDefaultHomeSpacePath(); - - NodeRef rootNodeRef = this.getNodeService().getRootNode(Repository.getStoreRef()); - List nodes = this.getSearchService().selectNodes(rootNodeRef, defaultHomeSpacePath, null, this.getNamespaceService(), false); - - if (nodes.size() == 0) - { - return getCompanyHomeSpace(); - } - - this.defaultHomeSpaceRef = nodes.get(0); - } - - return this.defaultHomeSpaceRef; - } - - /** - * Create the specified home space if it does not exist, and return the ID - * - * @param locationId Parent location - * @param spaceName Home space to create, can be null to simply return the parent - * @param oldHomeFolderRef the previous home space, for the case where the the user is being updated. - * It may not have changed. - * @param error True to throw an error if the space already exists, else ignore and return - * @return ID of the home space - */ - protected NodeRef createHomeSpace(String locationId, String spaceName, NodeRef oldHomeFolderRef, boolean error) - { - NodeRef homeSpaceNodeRef = null; - if (spaceName != null && spaceName.length() != 0) - { - NodeRef parentRef = new NodeRef(Repository.getStoreRef(), locationId); - - // check for existence of home space with same name - return immediately - // if it exists or throw an exception an give user chance to enter another name - NodeRef childRef = this.getNodeService().getChildByName(parentRef, ContentModel.ASSOC_CONTAINS, spaceName); - if (childRef != null) - { - if (childRef.equals(oldHomeFolderRef)) - { - return oldHomeFolderRef; - } - if (error) - { - throw new AlfrescoRuntimeException("A Home Space with the same name already exists."); - } - else - { - return childRef; - } - } - - // space does not exist already, create a new Space under it with - // the specified name - String qname = QName.createValidLocalName(spaceName); - ChildAssociationRef assocRef = this.getNodeService().createNode(parentRef, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, qname), - ContentModel.TYPE_FOLDER); - - NodeRef nodeRef = assocRef.getChildRef(); - - // set the name property on the node - this.getNodeService().setProperty(nodeRef, ContentModel.PROP_NAME, spaceName); - - if (logger.isDebugEnabled()) - logger.debug("Created Home Space for with name: " + spaceName); - - // apply the uifacets aspect - icon, title and description props - Map uiFacetsProps = new HashMap(3); - uiFacetsProps.put(ApplicationModel.PROP_ICON, CreateSpaceWizard.DEFAULT_SPACE_ICON_NAME); - uiFacetsProps.put(ContentModel.PROP_TITLE, spaceName); - this.getNodeService().addAspect(nodeRef, ApplicationModel.ASPECT_UIFACETS, uiFacetsProps); - - setupHomeSpacePermissions(nodeRef); - - // return the ID of the created space - homeSpaceNodeRef = nodeRef; - } - - return homeSpaceNodeRef; - } - - /** - * Setup the default permissions for this and other users on the Home Space - * - * @param homeSpaceRef Home Space reference - */ - private void setupHomeSpacePermissions(NodeRef homeSpaceRef) - { - // Admin Authority has full permissions by default (automatic - set in the permission config) - // give full permissions to the new user - getPermissionService().setPermission(homeSpaceRef, this.userName, getPermissionService().getAllPermission(), true); - - // by default other users will only have GUEST access to the space contents - // or whatever is configured as the default in the web-client-xml config - String permission = getDefaultPermission(); - if (permission != null && permission.length() != 0) - { - getPermissionService().setPermission(homeSpaceRef, getPermissionService().getAllAuthorities(), permission, true); - } - - // the new user is the OWNER of their own space and always has full permissions - getOwnableService().setOwner(homeSpaceRef, this.userName); - getPermissionService().setPermission(homeSpaceRef, getPermissionService().getOwnerAuthority(), getPermissionService().getAllPermission(), true); - - // now detach (if we did this first we could not set any permissions!) - getPermissionService().setInheritParentPermissions(homeSpaceRef, false); - } - - /** - * @return default permission string to set for other users for a new Home Space - */ - private String getDefaultPermission() - { - ClientConfigElement config = Application.getClientConfig(FacesContext.getCurrentInstance()); - return config.getHomeSpacePermission(); - } - - private void invalidateUserList() - { - UIContextService.getInstance(FacesContext.getCurrentInstance()).notifyBeans(); - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Throwable - { - // TODO: implement create new Person object from specified details - try - { - if (! this.password.equals(this.confirm)) - { - Utils.addErrorMessage(Application.getMessage(context, UsersDialog.ERROR_PASSWORD_MATCH)); - outcome = null; - } - - if (checkTenantUserName() == false) - { - outcome = null; - } - - if (outcome != null) - { - // create properties for Person type from submitted Form data - Map props = new HashMap(7, 1.0f); - setPersonPropertiesAndCreateHomeSpaceIfNeeded(props, null, context); - - // create the node to represent the Person - getPersonService().createPerson(props); - - // ensure the user can access their own Person object - // getPermissionService().setPermission(newPerson, this.userName, getPermissionService().getAllPermission(), true); - // Not required - now done by the person service. - - if (logger.isDebugEnabled()) - logger.debug("Created Person node for username: " + this.userName); - - // create the ACEGI Authentication instance for the new user - getAuthenticationService().createAuthentication(this.userName, this.password.toCharArray()); - - if (logger.isDebugEnabled()) - logger.debug("Created User Authentication instance for username: " + this.userName); - - if ((this.sizeQuota != null) && (this.sizeQuota < 0L)) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, UsersDialog.ERROR_NEGATIVE_QUOTA), this.sizeQuota)); - outcome = null; - } - else - { - putSizeQuotaProperty(this.userName, this.sizeQuota, this.sizeQuotaUnits); - } - } - invalidateUserList(); - } - catch (Throwable e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), ERROR), e.getMessage()), e); - outcome = null; - this.isFinished = false; - ReportedException.throwIfNecessary(e); - } - - if (outcome == null) - { - this.isFinished = false; - } - - return outcome; - } - - protected void setPersonPropertiesAndCreateHomeSpaceIfNeeded( - Map props, NodeRef oldHomeFolderRef, FacesContext context) - { - props.put(ContentModel.PROP_USERNAME, this.userName); - props.put(ContentModel.PROP_FIRSTNAME, this.firstName); - props.put(ContentModel.PROP_LASTNAME, this.lastName); - NodeRef homeSpaceNodeRef; - if (this.homeSpaceLocation != null && this.homeSpaceName.length() != 0) - { - // create new - props.put(ContentModel.PROP_HOME_FOLDER_PROVIDER, "userHomesHomeFolderProvider"); - homeSpaceNodeRef = createHomeSpace(this.homeSpaceLocation.getId(), this.homeSpaceName, oldHomeFolderRef, true); - } - else if (this.homeSpaceLocation != null) - { - // set to existing - first ensure it is NOT "User Homes" space! - if (this.defaultHomeSpaceRef.equals(this.homeSpaceLocation)) - { - throw new AlfrescoRuntimeException(Application.getMessage(context, MSG_ERROR_NEWUSER_HOME_SPACE)); - } - props.put(ContentModel.PROP_HOME_FOLDER_PROVIDER, "companyHomeFolderProvider"); // shared folder - homeSpaceNodeRef = this.homeSpaceLocation; - setupHomeSpacePermissions(homeSpaceNodeRef); - } - else - { - // default to Company Home - props.put(ContentModel.PROP_HOME_FOLDER_PROVIDER, "companyHomeFolderProvider"); // shared folder - homeSpaceNodeRef = getCompanyHomeSpace(); - } - - props.put(ContentModel.PROP_HOMEFOLDER, homeSpaceNodeRef); - props.put(ContentModel.PROP_EMAIL, this.email); - props.put(ContentModel.PROP_ORGID, this.companyId); - props.put(ContentModel.PROP_ORGANIZATION, this.organisation); - props.put(ContentModel.PROP_JOBTITLE, this.jobtitle); - props.put(ContentModel.PROP_LOCATION, this.location); - props.put(ContentModel.PROP_PRESENCEPROVIDER, this.presenceProvider); - props.put(ContentModel.PROP_PRESENCEUSERNAME, this.presenceUsername); - } - - @Override - public boolean getFinishButtonDisabled() - { - if (this.firstName != null && this.lastName != null && this.email != null && this.firstName.length() > 0 && this.lastName.length() > 0 && this.email.length() > 0) - { - return false; - } - return true; - } - - protected void putSizeQuotaProperty(String userName, Long quota, String quotaUnits) - { - if (quota != null) - { - if (quota >= 0L) - { - quota = convertToBytes(quota, quotaUnits); - } - else - { - // ignore negative quota - return; - } - } - - getContentUsageService().setUserQuota(userName, (quota == null ? -1 : quota)); - } - - protected long convertToBytes(long size, String units) - { - if (units != null) - { - if (units.equals(QUOTA_UNITS_KB)) - { - size = size * 1024L; - } - else if (units.equals(QUOTA_UNITS_MB)) - { - size = size * 1048576L; - } - else if (units.equals(QUOTA_UNITS_GB)) - { - size = size * 1073741824L; - } - } - return size; - } - - protected Pair convertFromBytes(long size) - { - String units = null; - if (size <= 0) - { - units = QUOTA_UNITS_GB; - } - else if (size < 999999) - { - size = (long)((double)size / 1024.0d); - units = QUOTA_UNITS_KB; - } - else if (size < 999999999) - { - size = (long)((double)size / 1048576.0d); - units = QUOTA_UNITS_MB; - } - else - { - size = (long)((double)size / 1073741824.0d); - units = QUOTA_UNITS_GB; - } - return new Pair(size, units); - } - - public boolean checkTenantUserName() - { - try - { - this.userName = PersonServiceImpl.updateUsernameForTenancy( - this.userName, getTenantService() - ); - return true; - } - catch(TenantDomainMismatchException e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), ERROR_DOMAIN_MISMATCH), e.getTenantA(), e.getTenantB())); - return false; - } - } - - public Map getPersonPropertiesImmutability() - { - return Collections.EMPTY_MAP; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/users/DeleteUserDialog.java b/war/src/main/java/org/alfresco/web/bean/users/DeleteUserDialog.java deleted file mode 100644 index b2aafffb59..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/DeleteUserDialog.java +++ /dev/null @@ -1,304 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ContentModel; -import org.alfresco.query.PagingRequest; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.security.AuthenticationService; -import org.alfresco.service.cmr.security.PersonService; -import org.alfresco.service.cmr.security.PersonService.PersonInfo; -import org.alfresco.service.namespace.QName; -import org.alfresco.util.ISO9075; -import org.alfresco.util.Pair; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.MapNode; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class DeleteUserDialog extends BaseDialogBean -{ - - private static final long serialVersionUID = -4977064287365766306L; - - private static Log logger = LogFactory.getLog(DeleteUserDialog.class); - - private static final String ERROR_DELETE = "error_delete_user"; - - private static final String BUTTON_YES = "yes"; - - private static final String MSG_TITLE_DELETE_USER = "title_delete_user"; - - private static final String BUTTON_NO = "no"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - transient private AuthenticationService authenticationService; - - private List users = Collections. emptyList(); - - transient private PersonService personService; - - private Node person = null; - - private String searchCriteria = null; - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - try - { - String userName = (String) getPerson().getProperties().get("userName"); - - // delete the associated Person - getPersonService().deletePerson(userName); - - // re-do the search to refresh the list - search(); - } - catch (Throwable e) - { - // rollback the transaction - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, ERROR_DELETE), e.getMessage()), e); - ReportedException.throwIfNecessary(e); - } - - return outcome; - } - - public String search() - { - - if (this.searchCriteria == null || this.searchCriteria.length() == 0) - { - this.users = Collections. emptyList(); - } - else - { - FacesContext context = FacesContext.getCurrentInstance(); - UserTransaction tx = null; - - try - { - tx = Repository.getUserTransaction(context, true); - tx.begin(); - - // define the query to find people by their first or last name - String search = ISO9075.encode(this.searchCriteria); - List> filter = Utils.generatePersonFilter(search); - - if (logger.isDebugEnabled()) - { - logger.debug("Query filter: " + filter); - } - - List persons = getPersonService().getPeople( - filter, - true, - Utils.generatePersonSort(), - new PagingRequest(Utils.getPersonMaxResults(), null) - ).getPage(); - - if (logger.isDebugEnabled()) - { - logger.debug("Found " + persons.size() + " users"); - } - - this.users = new ArrayList(persons.size()); - - for (PersonInfo person : persons) - { - // create our Node representation - MapNode node = new MapNode(person.getNodeRef()); - - // set data binding properties - // this will also force initialisation of the props now during the UserTransaction - // it is much better for performance to do this now rather than during page bind - Map props = node.getProperties(); - props.put("fullName", ((String) props.get("firstName")) + ' ' + ((String) props.get("lastName"))); - NodeRef homeFolderNodeRef = (NodeRef) props.get("homeFolder"); - if (homeFolderNodeRef != null) - { - props.put("homeSpace", homeFolderNodeRef); - } - - this.users.add(node); - } - - // commit the transaction - tx.commit(); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, Repository.ERROR_NODEREF), new Object[] { "root" })); - this.users = Collections. emptyList(); - try - { - if (tx != null) - { - tx.rollback(); - } - } - catch (Exception tex) - { - } - } - catch (Exception err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, Repository.ERROR_GENERIC), err.getMessage()), err); - this.users = Collections. emptyList(); - try - { - if (tx != null) - { - tx.rollback(); - } - } - catch (Exception tex) - { - } - } - } - - // return null to stay on the same page - return null; - } - - public void setupUserAction(ActionEvent event) - { - UIActionLink link = (UIActionLink) event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - if (logger.isDebugEnabled()) - logger.debug("Setup for action, setting current Person to: " + id); - - try - { - // create the node ref, then our node representation - NodeRef ref = new NodeRef(Repository.getStoreRef(), id); - Node node = new Node(ref); - - // remember the Person node - setPerson(node); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] { id })); - } - } - else - { - setPerson(null); - } - } - - /** - *@return authenticationService - */ - public AuthenticationService getAuthenticationService() - { - //check for null for cluster environment - if (authenticationService == null) - { - authenticationService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getAuthenticationService(); - } - return authenticationService; - } - - public void setAuthenticationService(AuthenticationService authenticationService) - { - this.authenticationService = authenticationService; - } - - public PersonService getPersonService() - { - if (personService == null) - { - personService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPersonService(); - } - return personService; - } - - public void setPersonService(PersonService personService) - { - this.personService = personService; - } - - public Node getPerson() - { - return person; - } - - public void setPerson(Node person) - { - this.person = person; - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), BUTTON_NO); - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), BUTTON_YES); - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_TITLE_DELETE_USER) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) - + getPerson().getProperties().get("userName") + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/users/EditContentUserRolesDialog.java b/war/src/main/java/org/alfresco/web/bean/users/EditContentUserRolesDialog.java deleted file mode 100644 index 5c88487e41..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/EditContentUserRolesDialog.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.faces.model.DataModel; - -import org.alfresco.web.bean.dialog.BaseDialogBean; - -public class EditContentUserRolesDialog extends BaseDialogBean -{ - private static final long serialVersionUID = -1690749440382024258L; - - ContentUsersBean contentUsersBean; - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - public ContentUsersBean getContentUsersBean() - { - return contentUsersBean; - } - - public void setContentUsersBean(ContentUsersBean contentUsersBean) - { - this.contentUsersBean = contentUsersBean; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - contentUsersBean.finishOK(); - return outcome; - } - - public void addRole(ActionEvent event) - { - contentUsersBean.addRole(event); - } - - public void setupUserAction(ActionEvent event) - { - contentUsersBean.setupUserAction(event); - } - - public void removeRole(ActionEvent event) - { - contentUsersBean.removeRole(event); - } - - public DataModel getPersonRolesDataModel() - { - return contentUsersBean.getPersonRolesDataModel(); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/users/EditFileDialog.java b/war/src/main/java/org/alfresco/web/bean/users/EditFileDialog.java deleted file mode 100644 index 2f9750f823..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/EditFileDialog.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.bean.dialog.BaseDialogBean; - -public class EditFileDialog extends BaseDialogBean -{ - - private static final long serialVersionUID = -4237199472024493269L; - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - // TODO Auto-generated method stub - return null; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/users/EditUserDetailsDialog.java b/war/src/main/java/org/alfresco/web/bean/users/EditUserDetailsDialog.java deleted file mode 100644 index 24755f3b6d..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/EditUserDetailsDialog.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.repository.AssociationRef; -import org.alfresco.service.cmr.repository.ContentReader; -import org.alfresco.service.cmr.repository.ContentService; -import org.alfresco.service.cmr.repository.ContentWriter; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; - -/** - * @author YanO - * - */ -public class EditUserDetailsDialog extends BaseDialogBean -{ - private static final long serialVersionUID = 8663254425262484L; - - private Node person; - protected UsersBeanProperties properties; - private NodeRef photoRef; - private String personDescription; - - /** - * @param properties the properties to set - */ - public void setProperties(UsersBeanProperties properties) - { - this.properties = properties; - } - - @Override - public void init(Map parameters) - { - super.init(parameters); - this.person = this.properties.getPerson(); - this.photoRef = null; - this.personDescription = null; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - try - { - ServiceRegistry services = Repository.getServiceRegistry(FacesContext.getCurrentInstance()); - DictionaryService dd = services.getDictionaryService(); - Map props = getNodeService().getProperties(getPerson().getNodeRef()); - for (String key : getPerson().getProperties().keySet()) - { - QName propQName = QName.createQName(key); - if (dd.getProperty(propQName) == null || dd.getProperty(propQName).isProtected() == false) - { - props.put(propQName, (Serializable)getPerson().getProperties().get(key)); - } - } - - // persist all property changes - NodeRef personRef = getPerson().getNodeRef(); - this.getNodeService().setProperties(personRef, props); - - // save person description content field - if (this.personDescription != null) - { - ContentService cs = services.getContentService(); - ContentWriter writer = cs.getWriter(personRef, ContentModel.PROP_PERSONDESC, true); - writer.setMimetype(MimetypeMap.MIMETYPE_HTML); - writer.putContent(this.personDescription); - } - - // setup user avatar association - if (this.photoRef != null) - { - List refs = this.getNodeService().getTargetAssocs(personRef, ContentModel.ASSOC_AVATAR); - // remove old association if it exists - if (refs.size() == 1) - { - NodeRef existingRef = refs.get(0).getTargetRef(); - this.getNodeService().removeAssociation( - personRef, existingRef, ContentModel.ASSOC_AVATAR); - } - // setup new association - this.getNodeService().createAssociation(personRef, this.photoRef, ContentModel.ASSOC_AVATAR); - } - - // if the above calls were successful, then reset Person Node in the session - Application.getCurrentUser(context).reset(); - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, Repository.ERROR_GENERIC), err.getMessage()), err); - outcome = null; - ReportedException.throwIfNecessary(err); - } - return outcome; - } - - public Node getPerson() - { - return person; - } - - public String getEmail() - { - Object value = person.getProperties().get(ContentModel.PROP_EMAIL); - return value == null ? null : value.toString(); - } - - public void setEmail(String email) - { - person.getProperties().put(ContentModel.PROP_EMAIL.toString(), email); - } - - public String getFirstName() - { - Object value = person.getProperties().get(ContentModel.PROP_FIRSTNAME); - return value == null ? null : value.toString(); - } - - public void setFirstName(String firstName) - { - person.getProperties().put(ContentModel.PROP_FIRSTNAME.toString(), firstName); - } - - public String getLastName() - { - Object value = person.getProperties().get(ContentModel.PROP_LASTNAME); - return value == null ? null : value.toString(); - } - - public String getPersonDescription() - { - if (personDescription == null) - { - ContentService cs = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getContentService(); - ContentReader reader = cs.getReader(this.person.getNodeRef(), ContentModel.PROP_PERSONDESC); - if (reader != null && reader.exists()) - { - personDescription = reader.getContentString(); - } - } - return personDescription; - } - - public void setPersonDescription(String s) - { - this.personDescription = s; - } - - public void setLastName(String lastName) - { - person.getProperties().put(ContentModel.PROP_LASTNAME.toString(), lastName); - } - - public Map getPersonProperties() - { - return person.getProperties(); - } - - public NodeRef getPersonPhotoRef() - { - if (this.photoRef == null) - { - List refs = this.getNodeService().getTargetAssocs(person.getNodeRef(), ContentModel.ASSOC_AVATAR); - if (refs.size() == 1) - { - this.photoRef = refs.get(0).getTargetRef(); - } - } - return this.photoRef; - } - - public void setPersonPhotoRef(NodeRef ref) - { - this.photoRef = ref; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/users/EditUserRolesDialog.java b/war/src/main/java/org/alfresco/web/bean/users/EditUserRolesDialog.java deleted file mode 100644 index 334c789cdb..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/EditUserRolesDialog.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.faces.model.DataModel; - -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; - -public class EditUserRolesDialog extends BaseDialogBean { - - private static final long serialVersionUID = 614541023231055676L; - - private static final String MSG_MODIFY_USER_ROLE = "modify_user_roles"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - SpaceUsersBean spaceUsersBean; - - @Override - public boolean getFinishButtonDisabled() { - return false; - } - - public SpaceUsersBean getSpaceUsersBean() { - return spaceUsersBean; - } - - public void setSpaceUsersBean(SpaceUsersBean spaceUsersBean) { - this.spaceUsersBean = spaceUsersBean; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception { - spaceUsersBean.finishOK(); - return outcome; - } - - public void addRole(ActionEvent event) { - spaceUsersBean.addRole(event); - } - - public void setupUserAction(ActionEvent event) { - spaceUsersBean.setupUserAction(event); - } - - public void removeRole(ActionEvent event) { - spaceUsersBean.removeRole(event); - } - - public DataModel getPersonRolesDataModel() { - return spaceUsersBean.getPersonRolesDataModel(); - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_MODIFY_USER_ROLE) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) - + spaceUsersBean.getPersonName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/users/EditUserWizard.java b/war/src/main/java/org/alfresco/web/bean/users/EditUserWizard.java deleted file mode 100644 index 76805e69cd..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/EditUserWizard.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.QName; -import org.alfresco.util.Pair; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * @author YanO - * - */ -public class EditUserWizard extends CreateUserWizard -{ - private static final long serialVersionUID = 7529989488476324511L; - - private static Log logger = LogFactory.getLog(EditUserWizard.class); - - protected UsersBeanProperties properties; - - /** - * @param properties the properties to set - */ - public void setProperties(UsersBeanProperties properties) - { - this.properties = properties; - } - - @Override - public void init(Map arg0) - { - super.init(arg0); - - // set values for edit mode - Map props = properties.getPerson().getProperties(); - - this.firstName = (String) props.get("firstName"); - this.lastName = (String) props.get("lastName"); - this.userName = (String) props.get("userName"); - this.email = (String) props.get("email"); - this.companyId = (String) props.get("organizationId"); - this.organisation = (String) props.get("organization"); - this.jobtitle = (String) props.get("jobtitle"); - this.location = (String) props.get("location"); - this.presenceProvider = (String) props.get("presenceProvider"); - this.presenceUsername = (String) props.get("presenceUsername"); - this.sizeQuota = (Long) props.get("sizeQuota"); - if (this.sizeQuota != null && this.sizeQuota == -1L) - { - this.sizeQuota = null; - } - - if (this.sizeQuota != null) - { - Pair size = convertFromBytes(this.sizeQuota); - this.sizeQuota = size.getFirst(); - this.sizeQuotaUnits = size.getSecond(); - } - - // calculate home space name and parent space Id from homeFolderId - this.homeSpaceLocation = null; // default to Company root space - NodeRef homeFolderRef = (NodeRef) props.get("homeFolder"); - if (homeFolderRef != null && this.getNodeService().exists(homeFolderRef) == true) - { - ChildAssociationRef childAssocRef = this.getNodeService().getPrimaryParent(homeFolderRef); - NodeRef parentRef = childAssocRef.getParentRef(); - if (this.getNodeService().getRootNode(Repository.getStoreRef()).equals(parentRef) == false) - { - this.homeSpaceLocation = parentRef; - this.homeSpaceName = Repository.getNameForNode(getNodeService(), homeFolderRef); - } - else - { - this.homeSpaceLocation = homeFolderRef; - } - } - - if (logger.isDebugEnabled()) - logger.debug("Edit user home space location: " + homeSpaceLocation + " home space name: " + homeSpaceName); - - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - try - { - // update the existing node in the repository - NodeRef nodeRef = properties.getPerson().getNodeRef(); - - // Note: The previous approach was to try a move the home folder if changed, - // but this was problematic as other users that shared the same folder - // moved too. We cannot tell if it is shared. Decided it is better to just - // create a new folder or reuse the folder pointed to just like the initial - // creation in CreateUserWizard. It is always possible to move the contents - // of the old home folder by hand later. - Map props = this.getNodeService().getProperties(nodeRef); - NodeRef oldHomeFolderRef = (NodeRef) this.getNodeService().getProperty(nodeRef, ContentModel.PROP_HOMEFOLDER); - if (oldHomeFolderRef != null && getNodeService().exists(oldHomeFolderRef) == false) - { - oldHomeFolderRef = null; - } - setPersonPropertiesAndCreateHomeSpaceIfNeeded(props, oldHomeFolderRef, context); - - // update the node that represents the Person - this.getNodeService().setProperties(nodeRef, props); - - // TODO: RESET HomeSpace Ref found in top-level navigation bar! - // NOTE: not need cos only admin can do this? - - if ((this.sizeQuota != null) && (this.sizeQuota < 0L)) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, UsersDialog.ERROR_NEGATIVE_QUOTA), this.sizeQuota)); - outcome = null; - } - else - { - putSizeQuotaProperty(this.userName, this.sizeQuota, this.sizeQuotaUnits); - } - } - catch (Throwable e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), ERROR), e.getMessage()), e); - outcome = null; - ReportedException.throwIfNecessary(e); - } - - if (outcome == null) - { - this.isFinished = false; - } - - return outcome; - } - - @Override - public Map getPersonPropertiesImmutability() - { - return this.properties.getImmutability(); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/users/EmailSpaceUsersDialog.java b/war/src/main/java/org/alfresco/web/bean/users/EmailSpaceUsersDialog.java deleted file mode 100644 index 371194aa2f..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/EmailSpaceUsersDialog.java +++ /dev/null @@ -1,629 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.security.AccessPermission; -import org.alfresco.service.cmr.security.AccessStatus; -import org.alfresco.service.cmr.security.AuthorityService; -import org.alfresco.service.cmr.security.AuthorityType; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.cmr.security.PersonService; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.IContextListener; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.TemplateMailHelperBean; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.MapNode; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.repository.User; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.repo.WebResources; -import org.alfresco.web.ui.repo.component.UIUserGroupPicker; -import org.alfresco.web.ui.repo.component.UIUserGroupPicker.PickerEvent; -import org.springframework.mail.javamail.JavaMailSender; - -/** - * Dialog bean managing the state for the Email Space Users page. Calculates the user/groups - * that are invited to a space and builds the data structures needed to display and modify - * the list in the web-client UI. Notifies the selected user/groups with a templatable email. - * - * @author Kevin Roast - */ -public class EmailSpaceUsersDialog extends BaseDialogBean implements IContextListener -{ - private static final long serialVersionUID = 7925542142116904285L; - - private static final String PROP_DUPLICATE = "duplicate"; - private static final String PROP_PARENT = "parent"; - private static final String PROP_ID = "id"; - private static final String PROP_ISGROUP = "isGroup"; - private static final String PROP_ICON = "icon"; - private static final String PROP_FULLNAME = "fullName"; - private static final String PROP_ROLES = "roles"; - private static final String PROP_EXPANDED = "expanded"; - private static final String PROP_SELECTED = "selected"; - private static final String PROP_USERNAME = "userName"; - - /** Injected Bean references */ - transient private PermissionService permissionService; - transient private PersonService personService; - transient private AuthorityService authorityService; - transient private JavaMailSender mailSender; - - /** Helper providing template based mailing facilities */ - protected TemplateMailHelperBean mailHelper; - - /** List of user/group property map/node instances */ - private List usersGroups = null; - - /** Quick lookup table of authority to user/group instance */ - private Map userGroupLookup = new HashMap(); - - - /** - * Default constructor - */ - public EmailSpaceUsersDialog() - { - UIContextService.getInstance(FacesContext.getCurrentInstance()).registerBean(this); - } - - /** - * Setup the dialog - */ - public void init(Map parameters) - { - super.init(parameters); - - mailHelper = new TemplateMailHelperBean(); - mailHelper.setMailSender(getMailSender()); - mailHelper.setNodeService(getNodeService()); - } - - /** - * @see org.alfresco.web.bean.dialog.BaseDialogBean#finishImpl(javax.faces.context.FacesContext, java.lang.String) - */ - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - // get the space ref this mail applies to - NodeRef spaceRef = getSpace().getNodeRef(); - - // calculate the 'from' email address - User user = Application.getCurrentUser(context); - String from = (String)this.getNodeService().getProperty(user.getPerson(), ContentModel.PROP_EMAIL); - if (from == null || from.length() == 0) - { - // if the user does not have an email address get the default one from the config service - from = Application.getClientConfig(context).getFromEmailAddress(); - } - - Set mailedAuthorities = new HashSet(usersGroups.size()); - - // walk the list of users/groups to notify - handle duplicates along the way - for (Map node : usersGroups) - { - String authority = (String)node.get(PROP_USERNAME); - boolean selected = (Boolean)node.get(PROP_SELECTED); - - // if User, email then, else if Group get all members and email them - AuthorityType authType = AuthorityType.getAuthorityType(authority); - if (authType.equals(AuthorityType.USER)) - { - if (selected == true && this.getPersonService().personExists(authority)) - { - if (mailedAuthorities.contains(authority) == false) - { - this.mailHelper.notifyUser( - this.getPersonService().getPerson(authority), spaceRef, from, (String)node.get(PROP_ROLES)); - mailedAuthorities.add(authority); - } - } - } - else if (authType.equals(AuthorityType.GROUP)) - { - // is the group expanded? if so we'll deal with the child authorities instead - boolean expanded = (Boolean)node.get(PROP_EXPANDED); - if (expanded == false && selected == true) - { - // notify all members of the group - Set users = this.getAuthorityService().getContainedAuthorities(AuthorityType.USER, authority, false); - for (String userAuth : users) - { - if (this.getPersonService().personExists(userAuth) == true) - { - if (mailedAuthorities.contains(userAuth) == false) - { - this.mailHelper.notifyUser( - this.getPersonService().getPerson(userAuth), spaceRef, from, (String)node.get(PROP_ROLES)); - mailedAuthorities.add(userAuth); - } - } - } - } - } - } - - return outcome; - } - - - // ------------------------------------------------------------------------------ - // IContextListener implementation - - /** - * @see org.alfresco.web.app.context.IContextListener#contextUpdated() - */ - public void contextUpdated() - { - this.usersGroups = null; - this.userGroupLookup = new HashMap(); - } - - /** - * @see org.alfresco.web.app.context.IContextListener#areaChanged() - */ - public void areaChanged() - { - // nothing to do - } - - /** - * @see org.alfresco.web.app.context.IContextListener#spaceChanged() - */ - public void spaceChanged() - { - // nothing to do - } - - // ------------------------------------------------------------------------------ - // Bean Getters and Setters - - /** - * @param permissionService The PermissionService to set - */ - public void setPermissionService(PermissionService permissionService) - { - this.permissionService = permissionService; - } - - protected PermissionService getPermissionService() - { - if (permissionService == null) - { - permissionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPermissionService(); - } - return permissionService; - } - - /** - * @param personService The PersonService to set - */ - public void setPersonService(PersonService personService) - { - this.personService = personService; - } - - protected PersonService getPersonService() - { - if (personService == null) - { - personService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPersonService(); - } - return personService; - } - - /** - * @param mailSender The JavaMailSender to set. - */ - public void setMailSender(JavaMailSender mailSender) - { - this.mailSender = mailSender; - } - - protected JavaMailSender getMailSender() - { - if (mailSender == null) - { - mailSender = (JavaMailSender) FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), "mailService"); - } - return mailSender; - } - - /** - * @param authorityService The AuthorityService to set. - */ - public void setAuthorityService(AuthorityService authorityService) - { - this.authorityService = authorityService; - } - - protected AuthorityService getAuthorityService() - { - if (authorityService == null) - { - authorityService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getAuthorityService(); - } - return authorityService; - } - - /** - * @return The space to email users for - */ - public Node getSpace() - { - return this.browseBean.getActionSpace(); - } - - /** - * Return the List of objects representing the Users and Groups invited to this space. - * The picker is then responsible for rendering a view to represent those users and groups - * which allows the users to select and deselect users and groups, also to expand groups - * to show sub-groups and users. - * - * @return List of Map objects representing the users/groups assigned to the current space - */ - public List getUsersGroups() - { - if (this.usersGroups == null) - { - FacesContext context = FacesContext.getCurrentInstance(); - - UserTransaction tx = null; - try - { - tx = Repository.getUserTransaction(context, true); - tx.begin(); - - // Return all the permissions set against the current node for any authentication - // instance (user/group), walking the parent space inheritance chain. - // Then combine them into a single list for each authentication found. - final String currentAuthority = Application.getCurrentUser(context).getUserName(); - Map> permissionMap = AuthenticationUtil.runAs(new RunAsWork>>() - { - public Map> doWork() throws Exception - { - NodeRef spaceRef = getSpace().getNodeRef(); - Map> permissionMap = new HashMap>(8, 1.0f); - while (spaceRef != null) - { - Set permissions = getPermissionService().getAllSetPermissions(spaceRef); - for (AccessPermission permission : permissions) - { - // we are only interested in Allow and not Guest/Everyone/owner - if (permission.getAccessStatus() == AccessStatus.ALLOWED && - (permission.getAuthorityType() == AuthorityType.USER || - permission.getAuthorityType() == AuthorityType.GROUP)) - { - String authority = permission.getAuthority(); - - if (currentAuthority.equals(authority) == false) - { - List userPermissions = permissionMap.get(authority); - if (userPermissions == null) - { - // create for first time - userPermissions = new ArrayList(4); - permissionMap.put(authority, userPermissions); - } - // add the permission name for this authority - userPermissions.add(permission.getPermission()); - } - } - } - - // walk parent inheritance chain until root or no longer inherits - if (getPermissionService().getInheritParentPermissions(spaceRef)) - { - spaceRef = getNodeService().getPrimaryParent(spaceRef).getParentRef(); - } - else - { - spaceRef = null; - } - } - return permissionMap; - } - }, AuthenticationUtil.SYSTEM_USER_NAME); - - // create the structure as a linked list for fast insert/removal of items - this.usersGroups = new LinkedList(); - - // for each authentication (username/group key) found we get the Person - // node represented by it and use that for our list databinding object - for (String authority : permissionMap.keySet()) - { - Map node = buildAuthorityMap(authority, UserMembersBean.roleListToString(context, permissionMap.get(authority))); - if (node != null) - { - this.usersGroups.add(node); - } - } - - // commit the transaction - tx.commit(); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - context, Repository.ERROR_NODEREF), new Object[] {refErr.getNodeRef()}) ); - this.usersGroups = Collections.emptyList(); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - context, Repository.ERROR_GENERIC), err.getMessage()), err ); - this.usersGroups = Collections.emptyList(); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - } - return this.usersGroups; - } - - /** - * @return TemplateMailHelperBean instance for this wizard - */ - public TemplateMailHelperBean getMailHelper() - { - return this.mailHelper; - } - - /** - * @return true if any authorities are selected, false otherwise - */ - public boolean getFinishButtonDisabled() - { - boolean disabled = true; - - if (this.usersGroups != null) - { - for (Map userGroup : this.usersGroups) - { - if (((Boolean)userGroup.get(PROP_EXPANDED)) == false && - ((Boolean)userGroup.get(PROP_SELECTED)) == true) - { - disabled = false; - break; - } - } - } - - return disabled; - } - - - // ------------------------------------------------------------------------------ - // Action Event Listeners - - /** - * Action handler for a user/group selector event - */ - public void userGroupSelectorAction(ActionEvent event) - { - if (event instanceof PickerEvent) - { - PickerEvent pickerEvent = (PickerEvent)event; - - // find the user/group this event represents - Map userGroup = null; - int index = 0; - for (; index authorities = getAuthorityService().getContainedAuthorities( - null, pickerEvent.Authority, true); - for (String authority : authorities) - { - if (currentAuthority.equals(authority) == false) - { - if (AuthorityType.getAuthorityType(authority) == AuthorityType.USER || - AuthorityType.getAuthorityType(authority) == AuthorityType.GROUP) - { - Map node = buildAuthorityMap(authority, (String)userGroup.get(PROP_ROLES)); - if (node != null) - { - node.put(PROP_PARENT, userGroup); - node.put(PROP_SELECTED, selected); - this.usersGroups.add(++index, node); - } - } - } - } - } - else - { - // remove the children for the group - for (index++; index props = ((MapNode)node).getProperties(); - props.put(PROP_FULLNAME, ((String)props.get("firstName")) + ' ' + ((String)props.get("lastName"))); - props.put(PROP_ICON, WebResources.IMAGE_PERSON); - props.put(PROP_ISGROUP, false); - } - } - else if (AuthorityType.getAuthorityType(authority) == AuthorityType.GROUP) - { - // need a map (dummy node) to represent props for this Group Authority - node = new HashMap(8, 1.0f); - - String groupDisplayName = this.authorityService.getAuthorityDisplayName(authority); - if (groupDisplayName == null || groupDisplayName.length() == 0) - { - if (authority.startsWith(PermissionService.GROUP_PREFIX) == true) - { - groupDisplayName = authority.substring(PermissionService.GROUP_PREFIX.length()); - } - else - { - groupDisplayName = authority; - } - } - - node.put(PROP_FULLNAME, groupDisplayName); - node.put(PROP_USERNAME, authority); - node.put(PROP_ID, authority); - node.put(PROP_ICON, WebResources.IMAGE_GROUP); - node.put(PROP_ISGROUP, true); - } - if (node != null) - { - // add the common properties - node.put(PROP_ROLES, roles); - node.put(PROP_PARENT, null); - node.put(PROP_EXPANDED, false); - - if (this.userGroupLookup.get(authority) != null) - { - // this authority already exists in the list somewhere else - mark as duplicate - node.put(PROP_DUPLICATE, true); - node.put(PROP_SELECTED, false); - } - else - { - // add to table for the first time, not a duplicate - this.userGroupLookup.put(authority, node); - node.put(PROP_DUPLICATE, false); - node.put(PROP_SELECTED, true); - } - } - - return node; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/users/MailInviteSpaceUsersWizard.java b/war/src/main/java/org/alfresco/web/bean/users/MailInviteSpaceUsersWizard.java deleted file mode 100644 index 56d46ca7df..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/MailInviteSpaceUsersWizard.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import java.util.Set; - -import org.alfresco.web.bean.spaces.InviteSpaceUsersWizard; - -/** - * MailInviteSpaceUsersWizard JSF managed bean. - * Overrides the InviteSpaceUsersWizard bean to return a list of Groups without EVERYONE. - */ -public class MailInviteSpaceUsersWizard extends InviteSpaceUsersWizard -{ - private static final long serialVersionUID = -68947308160920434L; - - @Override - protected Set getGroups(String search) - { - // get the groups without the EVERYONE group - return super.getGroups(search, false); - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/bean/users/RemoveContentUserDialog.java b/war/src/main/java/org/alfresco/web/bean/users/RemoveContentUserDialog.java deleted file mode 100644 index ba650890e4..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/RemoveContentUserDialog.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; - -/** - * Implementation of remove content user dialog. - * - * @author gavinc - */ -public class RemoveContentUserDialog extends BaseDialogBean -{ - private static final long serialVersionUID = -3090054828215666084L; - - private static final String MSG_REMOVE_USER = "remove_user"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - private ContentUsersBean contentUsersBean; - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - contentUsersBean.removeOK(); - - return outcome; - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_REMOVE_USER) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) - + this.getPersonName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - @Override - public String getContainerSubTitle() - { - return this.browseBean.getDocument().getName(); - } - - public void setupUserAction(ActionEvent event) - { - this.contentUsersBean.setupUserAction(event); - } - - public String getPersonName() - { - return this.contentUsersBean.getPersonName(); - } - - public void setPersonName(String personName) - { - this.contentUsersBean.setPersonName(personName); - } - - public ContentUsersBean getContentUsersBean() - { - return contentUsersBean; - } - - public void setContentUsersBean(ContentUsersBean contentUsersBean) - { - this.contentUsersBean = contentUsersBean; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/users/RemoveInvitedUserDialog.java b/war/src/main/java/org/alfresco/web/bean/users/RemoveInvitedUserDialog.java deleted file mode 100644 index a0600bf2f1..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/RemoveInvitedUserDialog.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; - -public class RemoveInvitedUserDialog extends BaseDialogBean -{ - - private static final long serialVersionUID = -7457234588814115434L; - - private static final String BUTTON_NO = "no"; - - private static final String BUTTON_YES = "yes"; - - private static final String MSG_REMOVE_USER = "remove_user"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - private SpaceUsersBean spaceUsersBean; - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return spaceUsersBean.removeOK(); - } - - public void setupUserAction(ActionEvent event) - { - spaceUsersBean.setupUserAction(event); - } - - public String getPersonName() - { - return spaceUsersBean.getPersonName(); - } - - public void setPersonName(String personName) - { - this.spaceUsersBean.setPersonName(personName); - } - - public SpaceUsersBean getSpaceUsersBean() - { - return spaceUsersBean; - } - - public void setSpaceUsersBean(SpaceUsersBean spaceUsersBean) - { - this.spaceUsersBean = spaceUsersBean; - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), BUTTON_NO); - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), BUTTON_YES); - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_REMOVE_USER) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) + spaceUsersBean.getPersonName() - + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/users/SpaceUsersBean.java b/war/src/main/java/org/alfresco/web/bean/users/SpaceUsersBean.java deleted file mode 100644 index c5796223ec..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/SpaceUsersBean.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import java.text.MessageFormat; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Node; - -/** - * Concrete implementation providing access to users of the current space. - * - * @author gavinc - */ -public class SpaceUsersBean extends UserMembersBean -{ - private static final long serialVersionUID = -4847219834289259559L; - - private final static String MSG_MANAGE_INVITED_USERS = "manage_invited_users"; - private final static String MSG_SPACE_OWNER = "space_owner"; - private final static String MSG_CLOSE= "close"; - private final static String MSG_LEFT_QUOTE = "left_qoute"; - private final static String MSG_RIGHT_QUOTE = "right_quote"; - - /** - * @return The space to work against - */ - public Node getNode() - { - return this.browseBean.getActionSpace(); - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - @Override - public Object getActionsContext() - { - return getNode(); - } - - @Override - public String getContainerTitle() - { - FacesContext fc = FacesContext.getCurrentInstance(); - return Application.getMessage(fc, MSG_MANAGE_INVITED_USERS) + " " + Application.getMessage(fc, MSG_LEFT_QUOTE) - + browseBean.getActionSpace().getName() + Application.getMessage(fc, MSG_RIGHT_QUOTE); - } - - @Override - public String getContainerSubTitle() - { - String pattern = Application.getMessage(FacesContext.getCurrentInstance(), MSG_SPACE_OWNER); - return MessageFormat.format(pattern, getOwner()); - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/users/UserConsoleDialog.java b/war/src/main/java/org/alfresco/web/bean/users/UserConsoleDialog.java deleted file mode 100644 index 4b85dcbbb0..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/UserConsoleDialog.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; - -public class UserConsoleDialog extends BaseDialogBean -{ - private static final long serialVersionUID = -217662039833342921L; - - private static final String MSG_CLOSE = "close"; - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/bean/users/UserMembersBean.java b/war/src/main/java/org/alfresco/web/bean/users/UserMembersBean.java deleted file mode 100644 index 294679a2f7..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/UserMembersBean.java +++ /dev/null @@ -1,959 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.faces.application.FacesMessage; -import javax.faces.component.UISelectOne; -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.faces.event.ValueChangeEvent; -import javax.faces.model.DataModel; -import javax.faces.model.ListDataModel; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.search.SearchService; -import org.alfresco.service.cmr.security.AccessPermission; -import org.alfresco.service.cmr.security.AccessStatus; -import org.alfresco.service.cmr.security.AuthorityService; -import org.alfresco.service.cmr.security.AuthorityType; -import org.alfresco.service.cmr.security.OwnableService; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.cmr.security.PersonService; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.IContextListener; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.BrowseBean; -import org.alfresco.web.bean.NavigationBean; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.dialog.FilterViewSupport; -import org.alfresco.web.bean.repository.MapNode; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.alfresco.web.ui.common.component.UIListItem; -import org.alfresco.web.ui.common.component.UIModeList; -import org.alfresco.web.ui.common.component.data.UIRichList; -import org.alfresco.web.ui.repo.WebResources; - -/** - * Bean backing the Manage Space/Content Permission pages. - * - * @author Kevin Roast - */ -public abstract class UserMembersBean extends BaseDialogBean implements IContextListener, FilterViewSupport -{ - private static final String MSG_SUCCESS_INHERIT_NOT = "success_not_inherit_permissions"; - private static final String MSG_SUCCESS_INHERIT = "success_inherit_permissions"; - - private static final String ERROR_DELETE = "error_remove_user"; - - private static final String OUTCOME_FINISH = "finish"; - - private static final String LOCAL = "local"; - private static final String INHERITED = "inherited"; - - private final static String MSG_CLOSE = "close"; - - private String filterMode = LOCAL; - - /** NodeService bean reference */ - transient private NodeService nodeService; - - /** SearchService bean reference */ - transient private SearchService searchService; - - /** PermissionService bean reference */ - transient private PermissionService permissionService; - - /** AuthorityService bean reference */ - transient private AuthorityService authorityService; - - /** PersonService bean reference */ - transient private PersonService personService; - - /** BrowseBean bean refernce */ - protected BrowseBean browseBean; - - /** OwnableService bean reference */ - transient private OwnableService ownableService; - - /** Component reference for Users RichList control */ - private UIRichList usersRichList; - - /** action context */ - private String personAuthority = null; - - /** action context */ - private String personName = null; - - /** datamodel for table of roles for current person */ - private transient DataModel personRolesDataModel = null; - - /** roles for current person */ - private List personRoles = null; - - - /** - * Default constructor - */ - public UserMembersBean() - { - UIContextService.getInstance(FacesContext.getCurrentInstance()).registerBean(this); - } - - - // ------------------------------------------------------------------------------ - // Abstract methods - - /** - * Returns the node that is being acted upon - * - * @return The node to manage permissions for - */ - public abstract Node getNode(); - - - // ------------------------------------------------------------------------------ - // Bean property getters and setters - - /** - * @param nodeService The NodeService to set. - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - protected NodeService getNodeService() - { - if (nodeService == null) - { - nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - } - return nodeService; - } - - /** - * @param searchService The search service - */ - public void setSearchService(SearchService searchService) - { - this.searchService = searchService; - } - - protected SearchService getSearchService() - { - if (searchService == null) - { - searchService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getSearchService(); - } - return searchService; - } - - /** - * @param permissionService The PermissionService to set. - */ - public void setPermissionService(PermissionService permissionService) - { - this.permissionService = permissionService; - } - - protected PermissionService getPermissionService() - { - if (permissionService == null) - { - permissionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPermissionService(); - } - return permissionService; - } - - /** - * @param authorityService The AuthorityService to set. - */ - public void setAuthorityService(AuthorityService authorityService) - { - this.authorityService = authorityService; - } - - protected AuthorityService getAuthorityService() - { - if (authorityService == null) - { - authorityService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getAuthorityService(); - } - return authorityService; - } - - /** - * @param ownableService The ownableService to set. - */ - public void setOwnableService(OwnableService ownableService) - { - this.ownableService = ownableService; - } - - protected OwnableService getOwnableService() - { - if (ownableService == null) - { - ownableService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getOwnableService(); - } - return ownableService; - } - - /** - * @param personService The personService to set. - */ - public void setPersonService(PersonService personService) - { - this.personService = personService; - } - - protected PersonService getPersonService() - { - if (personService == null) - { - personService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPersonService(); - } - return personService; - } - - /** - * @param browseBean The BrowseBean to set. - */ - public void setBrowseBean(BrowseBean browseBean) - { - this.browseBean = browseBean; - } - - /** - * @return Returns the usersRichList. - */ - public UIRichList getUsersRichList() - { - return this.usersRichList; - } - - /** - * @param usersRichList The usersRichList to set. - */ - public void setUsersRichList(UIRichList usersRichList) - { - this.usersRichList = usersRichList; - } - - /** - * Returns the properties for current Person roles JSF DataModel - * - * @return JSF DataModel representing the current Person roles - */ - public DataModel getPersonRolesDataModel() - { - if (this.personRolesDataModel == null) - { - this.personRolesDataModel = new ListDataModel(); - } - - if (this.personRolesDataModel.getWrappedData() == null) - { - this.personRolesDataModel.setWrappedData(this.personRoles); - } - - return this.personRolesDataModel; - } - - /** - * @return Returns the current person authority. - */ - public String getPersonAuthority() - { - return this.personAuthority; - } - - /** - * @param person The person person authority to set. - */ - public void setPersonAuthority(String person) - { - this.personAuthority = person; - } - - /** - * @return Returns the personName. - */ - public String getPersonName() - { - return this.personName; - } - - /** - * @param personName The personName to set. - */ - public void setPersonName(String personName) - { - this.personName = personName; - } - - /** - * @return true if the current user can change permissions on this Space - */ - public boolean getHasChangePermissions() - { - return getNode().hasPermission(PermissionService.CHANGE_PERMISSIONS); - } - - /** - * @return Returns the inherit parent permissions flag set for the current space. - */ - public boolean isInheritPermissions() - { - return this.getPermissionService().getInheritParentPermissions(getNode().getNodeRef()); - } - - /** - * @param inheritPermissions The inheritPermissions to set. - */ - public void setInheritPermissions(boolean inheritPermissions) - { - // stub - no impl as changes are made immediately using a ValueChanged listener - } - - /** - * Return the owner username - */ - public String getOwner() - { - return this.getOwnableService().getOwner(getNode().getNodeRef()); - } - - /** - * @return the list of user nodes for list data binding - */ - public List getUsers() - { - FacesContext context = FacesContext.getCurrentInstance(); - - boolean includeInherited = (this.filterMode.equals(INHERITED)); - - List personNodes = null; - - UserTransaction tx = null; - try - { - tx = Repository.getUserTransaction(context, true); - tx.begin(); - - // Return all the permissions set against the current node - // for any authentication instance (user/group). - // Then combine them into a single list for each authentication found. - Map> permissionMap = new HashMap>(8, 1.0f); - Set permissions = getPermissionService().getAllSetPermissions(getNode().getNodeRef()); - for (AccessPermission permission : permissions) - { - // we are only interested in Allow and not groups/owner etc. - if (permission.getAccessStatus() == AccessStatus.ALLOWED && - (permission.getAuthorityType() == AuthorityType.USER || - permission.getAuthorityType() == AuthorityType.GROUP || - permission.getAuthorityType() == AuthorityType.GUEST || - permission.getAuthorityType() == AuthorityType.EVERYONE)) - { - if (includeInherited || permission.isSetDirectly()) - { - String authority = permission.getAuthority(); - - List userPermissions = permissionMap.get(authority); - if (userPermissions == null) - { - // create for first time - userPermissions = new ArrayList(4); - permissionMap.put(authority, userPermissions); - } - // add the permission name for this authority - userPermissions.add(permission.getPermission()); - } - } - } - - // for each authentication (username/group key) found we get the Person - // node represented by it and use that for our list databinding object - personNodes = new ArrayList(permissionMap.size()); - for (String authority : permissionMap.keySet()) - { - // check if we are dealing with a person (User Authority) - if (AuthorityType.getAuthorityType(authority) == AuthorityType.GUEST || - getPersonService().personExists(authority)) - { - NodeRef nodeRef = getPersonService().getPerson(authority); - if (nodeRef != null) - { - // create our Node representation - MapNode node = new MapNode(nodeRef); - - // set data binding properties - // this will also force initialisation of the props now during the UserTransaction - // it is much better for performance to do this now rather than during page bind - Map props = node.getProperties(); - String firstName = (String)props.get("firstName"); - String lastName = (String)props.get("lastName"); - props.put("fullName", (firstName != null ? firstName : "") + ' ' + (lastName != null ? lastName : "")); - props.put("userNameLabel", props.get("userName")); - props.put("roles", roleListToString(context, permissionMap.get(authority))); - props.put("icon", WebResources.IMAGE_PERSON); - props.put("isGroup", Boolean.FALSE); - props.put("inherited", includeInherited); - - personNodes.add(node); - } - } - else - { - // need a map (dummy node) to represent props for this Group Authority - Map node = new HashMap(8, 1.0f); - - String groupDisplayName = getAuthorityService().getAuthorityDisplayName(authority); - if (groupDisplayName == null || groupDisplayName.length() == 0) - { - if (authority.startsWith(PermissionService.GROUP_PREFIX) == true) - { - groupDisplayName = authority.substring(PermissionService.GROUP_PREFIX.length()); - } - else - { - groupDisplayName = authority; - } - } - - node.put("fullName", groupDisplayName); - node.put("userNameLabel", groupDisplayName); - node.put("userName", authority); - node.put("id", authority); - node.put("roles", roleListToString(context, permissionMap.get(authority))); - node.put("icon", WebResources.IMAGE_GROUP); - node.put("isGroup", Boolean.TRUE); - node.put("inherited", includeInherited); - - personNodes.add(node); - } - } - - // commit the transaction - tx.commit(); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - context, Repository.ERROR_NODEREF), new Object[] {refErr.getNodeRef()}) ); - personNodes = Collections.emptyList(); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - context, Repository.ERROR_GENERIC), err.getMessage()), err ); - personNodes = Collections.emptyList(); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - - return personNodes; - } - - /** - * Convert a list of user Roles to a comma separated string list. Each individual role - * will be looked up in message bundle to convert to a human readable string value. - * - * @param context FacesContext - * @param list List of Role names - * - * @return Comma separated string of human readable roles - */ - public static String roleListToString(FacesContext context, List list) - { - StringBuilder buf = new StringBuilder(); - - if (list != null) - { - for (int i=0; i getFilterItems() - { - FacesContext context = FacesContext.getCurrentInstance(); - List items = new ArrayList(2); - - UIListItem item1 = new UIListItem(); - item1.setValue(INHERITED); - item1.setLabel(Application.getMessage(context, INHERITED)); - items.add(item1); - - UIListItem item2 = new UIListItem(); - item2.setValue(LOCAL); - item2.setLabel(Application.getMessage(context, LOCAL)); - items.add(item2); - - return items; - } - - /** - * @see org.alfresco.web.bean.dialog.FilterViewSupport#getFilterMode() - */ - public String getFilterMode() - { - return filterMode; - } - - /** - * @see org.alfresco.web.bean.dialog.FilterViewSupport#setFilterMode(java.lang.String) - */ - public void setFilterMode(final String filterMode) - { - this.filterMode = filterMode; - - // clear datalist cache ready to change results based on filter setting - contextUpdated(); - } - - - // ------------------------------------------------------------------------------ - // Action event handlers - - /** - * Action called to Close the dialog - */ - public String cancel() - { - UIContextService.getInstance(FacesContext.getCurrentInstance()).notifyBeans(); - return super.cancel(); - } - - /** - * Action event called by all actions that need to setup a Person context on - * the UserMembers bean before an action page is called. The context will be a - * Authority in setPersonAuthority() which can be retrieved on the action page from - * UserMembersBean.setPersonAuthority(). - */ - public void setupUserAction(ActionEvent event) - { - FacesContext context = FacesContext.getCurrentInstance(); - - UIActionLink link = (UIActionLink) event.getComponent(); - Map params = link.getParameterMap(); - String authority = params.get("userName"); - if (authority != null && authority.length() != 0) - { - try - { - if (this.getPersonService().personExists(authority)) - { - // create the node ref, then our node representation - NodeRef ref = getPersonService().getPerson(authority); - Node node = new Node(ref); - - // setup convience function for current user full name - String firstName = (String)node.getProperties().get(ContentModel.PROP_FIRSTNAME); - String lastName = (String)node.getProperties().get(ContentModel.PROP_LASTNAME); - setPersonName((firstName != null ? firstName : "") + ' ' + (lastName != null ? lastName : "")); - } - else - { - String label = params.get("userNameLabel"); - if (label == null || label.length() == 0) - { - label = authority; - } - - setPersonName(label); - } - - // setup roles for this Authority - List userPermissions = new ArrayList(4); - Set permissions = getPermissionService().getAllSetPermissions(getNode().getNodeRef()); - if (permissions != null) - { - for (AccessPermission permission : permissions) - { - // we are only interested in Allow permissions - if (permission.getAccessStatus() == AccessStatus.ALLOWED) - { - if (authority.equals(permission.getAuthority())) - { - // found a permission for this user authentiaction - PermissionWrapper wrapper = new PermissionWrapper( - permission.getPermission(), - Application.getMessage(context, permission.getPermission())); - userPermissions.add(wrapper); - } - } - } - } - // action context setup - this.personRolesDataModel = null; - this.personRoles = userPermissions; - setPersonAuthority(authority); - } - catch (Exception err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext - .getCurrentInstance(), Repository.ERROR_GENERIC), new Object[] { err.getMessage() })); - } - } - else - { - setPersonAuthority(null); - } - - // force refresh on return to this page - contextUpdated(); - } - - /** - * Inherit parent Space permissions value changed by the user - */ - public void inheritPermissionsValueChanged(ValueChangeEvent event) - { - try - { - // change the value to the new selected value - boolean inheritPermissions = (Boolean)event.getNewValue(); - this.getPermissionService().setInheritParentPermissions(getNode().getNodeRef(), inheritPermissions); - - // inform the user that the change occured - FacesContext context = FacesContext.getCurrentInstance(); - String msg; - if (inheritPermissions) - { - msg = Application.getMessage(context, MSG_SUCCESS_INHERIT); - } - else - { - msg = Application.getMessage(context, MSG_SUCCESS_INHERIT_NOT); - } - - // see if the user still has permissions to the node, if not, we need - // to go back to the root of the current "area" by simulating the user - // pressing the top level navigation button i.e. My Home - if (this.getPermissionService().hasPermission(getNode().getNodeRef(), - PermissionService.CHANGE_PERMISSIONS) == AccessStatus.ALLOWED) - { - FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg); - context.addMessage(event.getComponent().getClientId(context), facesMsg); - } - else - { - NavigationBean nb = (NavigationBean)FacesHelper.getManagedBean( - context, NavigationBean.BEAN_NAME); - if (nb != null) - { - try - { - nb.processToolbarLocation(nb.getToolbarLocation(), true); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NOHOME), - Application.getCurrentUser(context).getHomeSpaceId()), refErr ); - } - catch (Exception err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), - err.getMessage()), err); - } - } - } - } - catch (Throwable e) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), e.getMessage()), e); - } - } - - /** - * Action handler called when the Add Role button is pressed to process the current selection - */ - public void addRole(ActionEvent event) - { - UISelectOne rolePicker = (UISelectOne)event.getComponent().findComponent("roles"); - - String role = (String)rolePicker.getValue(); - if (role != null) - { - FacesContext context = FacesContext.getCurrentInstance(); - PermissionWrapper wrapper = new PermissionWrapper(role, Application.getMessage(context, role)); - this.personRoles.add(wrapper); - } - - // force refresh on return to this page - contextUpdated(); - } - - /** - * Action handler called when the Remove button is pressed to remove a role from current user - */ - public void removeRole(ActionEvent event) - { - PermissionWrapper wrapper = (PermissionWrapper)getPersonRolesDataModel().getRowData(); - if (wrapper != null) - { - this.personRoles.remove(wrapper); - } - - // force refresh on return to this page - contextUpdated(); - } - - /** - * Action handler called when the Finish button is clicked on the Edit User Roles page - */ - public String finishOK() - { - String outcome = OUTCOME_FINISH; - - FacesContext context = FacesContext.getCurrentInstance(); - - // persist new user permissions - if (this.personRoles != null && getPersonAuthority() != null) - { - UserTransaction tx = null; - try - { - tx = Repository.getUserTransaction(context); - tx.begin(); - - // clear the currently set permissions for this user - // and add each of the new permissions in turn - final NodeRef nodeRef = getNode().getNodeRef(); - if (this.getPermissionService().hasPermission(nodeRef, PermissionService.CHANGE_PERMISSIONS) == AccessStatus.ALLOWED) - { - AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork() { - public Object doWork() throws Exception - { - getPermissionService().clearPermission(nodeRef, getPersonAuthority()); - for (PermissionWrapper wrapper : personRoles) - { - getPermissionService().setPermission( - nodeRef, - getPersonAuthority(), - wrapper.getPermission(), - true); - } - return null; - } - - }, AuthenticationUtil.getSystemUserName()); - } - - tx.commit(); - } - catch (Exception err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - context, Repository.ERROR_GENERIC), err.getMessage()), err ); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - - outcome = null; - } - } - - return outcome; - } - - /** - * Action handler called when the OK button is clicked on the Remove User page - */ - public String removeOK() - { - String outcome = getDefaultFinishOutcome(); - UserTransaction tx = null; - FacesContext context = FacesContext.getCurrentInstance(); - - try - { - tx = Repository.getUserTransaction(context); - tx.begin(); - - // remove the invited User - if (getPersonAuthority() != null) - { - // clear permissions for the specified Authority - this.getPermissionService().clearPermission(getNode().getNodeRef(), getPersonAuthority()); - } - - // commit the transaction - tx.commit(); - } - catch (Exception e) - { - // rollback the transaction - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext - .getCurrentInstance(), ERROR_DELETE), e.getMessage()), e); - } - - // see if the user still has permissions to the node, if not, we need - // to go back to the root of the current "area" by simulating the user - // pressing the top level navigation button i.e. My Home - if (this.getPermissionService().hasPermission(getNode().getNodeRef(), - PermissionService.CHANGE_PERMISSIONS) == AccessStatus.DENIED) - { - NavigationBean nb = (NavigationBean)FacesHelper.getManagedBean( - context, NavigationBean.BEAN_NAME); - if (nb != null) - { - try - { - nb.processToolbarLocation(nb.getToolbarLocation(), true); - outcome = "browse"; - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NOHOME), - Application.getCurrentUser(context).getHomeSpaceId()), refErr ); - } - catch (Exception err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), - err.getMessage()), err); - } - } - } - - return outcome; - } - - - // ------------------------------------------------------------------------------ - // Inner classes - - /** - * Wrapper class for list data model to display current roles for user - */ - public static class PermissionWrapper implements Serializable - { - private static final long serialVersionUID = 953727068432918977L; - - public PermissionWrapper(String permission, String label) - { - this.permission = permission; - this.label = label; - } - - public String getRole() - { - return this.label; - } - - public String getPermission() - { - return this.permission; - } - - private String label; - private String permission; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/users/UserPreferencesBean.java b/war/src/main/java/org/alfresco/web/bean/users/UserPreferencesBean.java deleted file mode 100644 index 712bfecf2f..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/UserPreferencesBean.java +++ /dev/null @@ -1,419 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.ResourceBundle; - -import javax.faces.context.FacesContext; -import javax.faces.model.SelectItem; - -import org.alfresco.service.cmr.ml.ContentFilterLanguagesService; -import org.alfresco.service.cmr.ml.MultilingualContentService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.NavigationBean; -import org.alfresco.web.bean.repository.PreferencesService; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.config.LanguagesConfigElement; -import org.springframework.extensions.config.Config; -import org.springframework.extensions.surf.util.I18NUtil; - -/** - * Simple bean backing the user preferences settings. - * - * @author Kevin Roast - */ -public class UserPreferencesBean implements Serializable -{ - private static final long serialVersionUID = -1262481849503163054L; - - public static final String PREF_INTERFACELANGUAGE = "interface-language"; - - private static final String PREF_STARTLOCATION = "start-location"; - private static final String PREF_CONTENTFILTERLANGUAGE = "content-filter-language"; - private static final String PREF_DOWNLOADAUTOMATICALLY = "download-automatically"; - - /** - * Remplacement message for set the filter at 'all languages'. - * Must be considered as a null value. - */ - public static final String MSG_CONTENTALLLANGUAGES = "content_all_languages"; - - /** content language locale selection */ - private String contentFilterLanguage = null; - - /** the injected MultilingualContentService */ - transient private MultilingualContentService multilingualContentService; - - /** the injected ContentFilterLanguagesService */ - transient private ContentFilterLanguagesService contentFilterLanguagesService; - - /** the injected NodeService */ - transient private NodeService nodeService; - - /** - * @return the list of available languages - */ - public SelectItem[] getLanguages() - { - // Get the item selection list for the list of languages - return getLanguageItems(); - } - - /** - * @return Returns the language selection for the current user session. - */ - public String getLanguage() - { - return Application.getLanguage(FacesContext.getCurrentInstance()).toString(); - } - - /** - * @param language The language selection to set. - */ - public void setLanguage(String language) - { - // set the language for the current session - Application.setLanguage(FacesContext.getCurrentInstance(), language); - - // save user preference - if (Application.getCurrentUser(FacesContext.getCurrentInstance()) != null) - { - PreferencesService.getPreferences().setValue(PREF_INTERFACELANGUAGE, language); - } - } - - /** - * @return current content filter language, or null if all languages was selected - */ - public String getContentFilterLanguage() - { - if (this.contentFilterLanguage == null) - { - Locale locale = (Locale) PreferencesService.getPreferences().getValue(PREF_CONTENTFILTERLANGUAGE); - - // Null means All Languages - if (locale == null) - { - this.contentFilterLanguage = null; - } - else - { - this.contentFilterLanguage = locale.toString(); - } - } - - // set the content filter locale on the core - I18NUtil.setContentLocale(I18NUtil.parseLocale(this.contentFilterLanguage)); - - return this.contentFilterLanguage; - } - - /** - * @param contentFilterLanguage A valid locale string or {@link #MSG_CONTENTALLLANGUAGES} - */ - public void setContentFilterLanguage(String contentFilterLanguage) - { - this.contentFilterLanguage = contentFilterLanguage; - Locale language = null; - if (contentFilterLanguage.equals(MSG_CONTENTALLLANGUAGES)) - { - // The generic "All Languages" was selected - persist this as a null - this.contentFilterLanguage = null; - } - else - { - // It should be a proper locale string - language = I18NUtil.parseLocale(contentFilterLanguage); - } - PreferencesService.getPreferences().setValue(PREF_CONTENTFILTERLANGUAGE, language); - - // set the content filter locale on the core - I18NUtil.setContentLocale(language); - - // Ensure a refresh - UIContextService.getInstance(FacesContext.getCurrentInstance()).notifyBeans(); - } - - /** - * @return list of items for the content filtering language selection include the label 'all langaguages' - */ - public SelectItem[] getContentFilterLanguages() - { - // Get the item selection list - return getContentFilterLanguages(true); - } - - /** - * @param includeAllLanguages if true, the list must include the label 'all languages' - * @return list of items for the content filtering language selection - */ - public SelectItem[] getContentFilterLanguages(boolean includeAllLanguages) - { - FacesContext fc = FacesContext.getCurrentInstance(); - ResourceBundle msg = Application.getBundle(fc); - - // get the list of filter languages - List languages = getContentFilterLanguagesService().getFilterLanguages(); - - // set the item selection list - SelectItem[] items = new SelectItem[(includeAllLanguages) ? languages.size() + 1 : languages.size()]; - int idx = 0; - - // include the item if needed - if (includeAllLanguages) - { - String allLanguagesStr = msg.getString(MSG_CONTENTALLLANGUAGES); - items[idx] = new SelectItem(MSG_CONTENTALLLANGUAGES, allLanguagesStr); - idx++; - } - - for (String lang : languages) - { - String label = getContentFilterLanguagesService().getLabelByCode(lang); - items[idx] = new SelectItem(lang, label); - idx++; - } - - return items; - } - - /** - * return the list of languages in which the given node hasn't be translated yet. - * - * @param translation the translatable node ref - * @param returnTranslationLanguage if true, return the language of the given translation. - * @return the list of languages - */ - public SelectItem[] getAvailablesContentFilterLanguages(NodeRef translation, boolean returnTranslationLanguage) - { - // get the list of missing translation of this node - List missingLocales = getMultilingualContentService().getMissingTranslations(translation, returnTranslationLanguage); - - // set the item selection list - SelectItem[] items = new SelectItem[missingLocales.size()]; - int idx = 0; - - for(Locale locale : missingLocales) - { - String label = getContentFilterLanguagesService().getLabelByCode(locale.getLanguage()); - - items[idx] = new SelectItem( - locale.toString(), - label); - idx++; - } - - return items; - } - - /** - * Helper to return the available language items - * - * @return Array of SelectItem objects - */ - private static SelectItem[] getLanguageItems() - { - FacesContext fc = FacesContext.getCurrentInstance(); - Config config = Application.getConfigService(fc).getConfig("Languages"); - LanguagesConfigElement langConfig = (LanguagesConfigElement)config.getConfigElement( - LanguagesConfigElement.CONFIG_ELEMENT_ID); - - List languages = langConfig.getLanguages(); - List items = new ArrayList(10); - - for (String locale : languages) - { - // get label associated to the locale - String label = langConfig.getLabelForLanguage(locale); - items.add(new SelectItem(locale, label)); - } - - return items.toArray(new SelectItem[items.size()]); - } - - /** - * @return the start location for this user (@see NavigationBean) - */ - public String getStartLocation() - { - String location = (String)PreferencesService.getPreferences().getValue(PREF_STARTLOCATION); - - if (location == null) - { - // default to value from client config - location = Application.getClientConfig(FacesContext.getCurrentInstance()).getInitialLocation(); - } - return location; - } - - /** - * @param location The current start location for this user (@see NavigationBean) - */ - public void setStartLocation(String location) - { - PreferencesService.getPreferences().setValue(PREF_STARTLOCATION, location); - } - - /** - * @return the list of available start locations - */ - public SelectItem[] getStartLocations() - { - FacesContext fc = FacesContext.getCurrentInstance(); - NavigationBean navigator = (NavigationBean)FacesHelper.getManagedBean(fc, "NavigationBean"); - ResourceBundle msg = Application.getBundle(fc); - - List locations = new ArrayList(4); - - // add My Alfresco location - locations.add(new SelectItem( - NavigationBean.LOCATION_MYALFRESCO, msg.getString(NavigationBean.MSG_MYALFRESCO))); - - // add My Home location - locations.add(new SelectItem( - NavigationBean.LOCATION_HOME, msg.getString(NavigationBean.MSG_MYHOME))); - - // add Company Home location if visible - if (navigator.getCompanyHomeVisible()) - { - locations.add(new SelectItem( - NavigationBean.LOCATION_COMPANY, msg.getString(NavigationBean.MSG_COMPANYHOME))); - } - - // add Guest Home location if visible - if (navigator.getGuestHomeVisible()) - { - locations.add(new SelectItem( - NavigationBean.LOCATION_GUEST, msg.getString(NavigationBean.MSG_GUESTHOME))); - } - - return locations.toArray(new SelectItem[locations.size()]); - } - - /** - * @return true if the Guest user is allowed to configure the user preferences - */ - public boolean getAllowGuestConfig() - { - return Application.getClientConfig(FacesContext.getCurrentInstance()).getAllowGuestConfig(); - } - - /** - * @return the multilingualContentService - */ - public MultilingualContentService getMultilingualContentService() - { - if (multilingualContentService == null) - { - multilingualContentService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getMultilingualContentService(); - } - - return multilingualContentService; - } - - /** - * @param multilingualContentService the multilingualContentService to set - */ - public void setMultilingualContentService( - MultilingualContentService multilingualContentService) - { - this.multilingualContentService = multilingualContentService; - } - - /** - * @return the nodeService - */ - public NodeService getNodeService() - { - if (nodeService == null) - { - nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - } - - return nodeService; - } - - /** - * @param nodeService the nodeService to set - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - /** - * @param contentFilterLanguagesService the contentFilterLanguagesService to set - */ - public void setContentFilterLanguagesService( - ContentFilterLanguagesService contentFilterLanguagesService) - { - this.contentFilterLanguagesService = contentFilterLanguagesService; - } - - /** - * @return the contentFilterLanguagesService - */ - ContentFilterLanguagesService getContentFilterLanguagesService() - { - if (contentFilterLanguagesService == null) - { - contentFilterLanguagesService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getContentFilterLanguagesService(); - } - return contentFilterLanguagesService; - } - - /** - * @return download files automatically for offline editing or not - */ - public boolean isDownloadAutomatically() - { - Boolean downloadAutomatically = (Boolean) PreferencesService.getPreferences().getValue(PREF_DOWNLOADAUTOMATICALLY); - if (downloadAutomatically == null) - { - return true; - } - else - { - return downloadAutomatically.booleanValue(); - } - } - - /** - * @param downloadAutomatically the boolean value to set - */ - public void setDownloadAutomatically(boolean downloadAutomatically) - { - PreferencesService.getPreferences().setValue(PREF_DOWNLOADAUTOMATICALLY, downloadAutomatically); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/users/UserProfileDialog.java b/war/src/main/java/org/alfresco/web/bean/users/UserProfileDialog.java deleted file mode 100644 index 7db797fe91..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/UserProfileDialog.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import java.text.MessageFormat; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; - -public class UserProfileDialog extends BaseDialogBean -{ - private static final String MSG_CLOSE = "close"; - private static final String MSG_USER_PROFILE = "user_profile_for"; - - private UsersBeanProperties properties; - - - /** - * @param properties the properties to set - */ - public void setProperties(UsersBeanProperties properties) - { - this.properties = properties; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), MSG_CLOSE); - } - - @Override - public String getContainerDescription() - { - // display description of user profile (full name etc.) - return MessageFormat.format( - Application.getMessage(FacesContext.getCurrentInstance(), MSG_USER_PROFILE), - this.properties.getPerson().getProperties().get(ContentModel.PROP_USERNAME)); - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/bean/users/UserShortcutsBean.java b/war/src/main/java/org/alfresco/web/bean/users/UserShortcutsBean.java deleted file mode 100644 index 0be22af087..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/UserShortcutsBean.java +++ /dev/null @@ -1,447 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.security.permissions.AccessDeniedException; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.security.AccessStatus; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.BrowseBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.PreferencesService; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.alfresco.web.ui.repo.component.shelf.UIShortcutsShelfItem; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * This bean manages the user defined list of Recent Spaces in the Shelf component. - * - * @author Kevin Roast - */ -public class UserShortcutsBean implements Serializable -{ - private static final long serialVersionUID = -2264529845476479897L; - - private static Log logger = LogFactory.getLog(UserShortcutsBean.class); - - /** The NodeService to be used by the bean */ - transient protected NodeService nodeService; - - /** The BrowseBean reference */ - protected BrowseBean browseBean; - - /** The PermissionService reference */ - transient private PermissionService permissionService; - - /** List of shortcut nodes */ - private List shortcuts = null; - - private static final String PREF_SHORTCUTS = "shortcuts"; - - - // ------------------------------------------------------------------------------ - // Bean property getters and setters - - /** - * @param nodeService The NodeService to set. - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - protected NodeService getNodeService() - { - if (nodeService == null) - { - nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - } - return nodeService; - } - - /** - * @param browseBean The BrowseBean to set. - */ - public void setBrowseBean(BrowseBean browseBean) - { - this.browseBean = browseBean; - } - - /** - * @param permissionService The PermissionService to set. - */ - public void setPermissionService(PermissionService permissionService) - { - this.permissionService = permissionService; - } - - protected PermissionService getPermissionService() - { - if (permissionService == null) - { - permissionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPermissionService(); - } - return permissionService; - } - - /** - * @return the List of shortcut Nodes - */ - public List getShortcuts() - { - if (this.shortcuts == null) - { - List shortcuts = null; - NodeRef prefRef = null; - UserTransaction tx = null; - boolean rollback = false; - try - { - FacesContext context = FacesContext.getCurrentInstance(); - tx = Repository.getUserTransaction(context); - tx.begin(); - - // get the shortcuts from the preferences for this user - shortcuts = getShortcutList(context); - if (shortcuts.size() != 0) - { - // each shortcut node ID is persisted as a list item in a well known property - this.shortcuts = new ArrayList(shortcuts.size()); - for (int i=0; i(5); - } - - if (rollback == false) - { - tx.commit(); - } - else - { - tx.rollback(); - } - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - - // if the count of accessable shortcuts is different to our original list then - // write the valid shortcut IDs back to correct invalid node refs - if (shortcuts != null && shortcuts.size() != this.shortcuts.size()) - { - try - { - shortcuts = new ArrayList(this.shortcuts.size()); - for (int i=0; i nodes) - { - this.shortcuts = nodes; - } - - - // ------------------------------------------------------------------------------ - // Action method handlers - - /** - * Action handler called when a new shortcut is to be added to the list - */ - public void createShortcut(ActionEvent event) - { - // TODO: add this action to the Details screen for Space and Document - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - try - { - NodeRef ref = new NodeRef(Repository.getStoreRef(), id); - Node node = new Node(ref); - - boolean foundShortcut = false; - for (int i=0; i shortcuts = getShortcutList(context); - shortcuts.add(node.getNodeRef().getId()); - PreferencesService.getPreferences(context).setValue(PREF_SHORTCUTS, (Serializable)shortcuts); - - // commit the transaction - tx.commit(); - - // add our new shortcut Node to the in-memory list - getShortcuts().add(node); - - if (logger.isDebugEnabled()) - logger.debug("Added node: " + node.getName() + " to the user shortcuts list."); - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - } - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {id}) ); - } - } - } - - /** - * Action handler bound to the user shortcuts Shelf component called when a node is removed - */ - public void removeShortcut(ActionEvent event) - { - UIShortcutsShelfItem.ShortcutEvent shortcutEvent = (UIShortcutsShelfItem.ShortcutEvent)event; - - // remove from persistent store - UserTransaction tx = null; - try - { - FacesContext context = FacesContext.getCurrentInstance(); - tx = Repository.getUserTransaction(context); - tx.begin(); - - List shortcuts = getShortcutList(context); - if (shortcuts.size() > shortcutEvent.Index) - { - // remove the shortcut from the saved list and persist back - shortcuts.remove(shortcutEvent.Index); - PreferencesService.getPreferences(context).setValue(PREF_SHORTCUTS, (Serializable)shortcuts); - - // commit the transaction - tx.commit(); - - // remove shortcut Node from the in-memory list - Node node = getShortcuts().remove(shortcutEvent.Index); - - if (logger.isDebugEnabled()) - logger.debug("Removed node: " + node.getName() + " from the user shortcuts list."); - } - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - } - - /** - * @return the List of shortcut values - will always return at least an empty List - */ - private static List getShortcutList(FacesContext context) - { - List shortcuts = null; - - Object prefValue = PreferencesService.getPreferences(context).getValue(PREF_SHORTCUTS); - if (prefValue instanceof List) - { - shortcuts = (List)prefValue; - } - else if (prefValue instanceof String) - { - shortcuts = new ArrayList(1); - shortcuts.add((String)prefValue); - } - - // handle missing and empty (immutable) list collection - if (shortcuts == null || shortcuts.size() == 0) - { - shortcuts = new ArrayList(1); - } - return shortcuts; - } - - /** - * Action handler bound to the user shortcuts Shelf component called when a node is clicked - */ - public void click(ActionEvent event) - { - // work out which node was clicked from the event data - UIShortcutsShelfItem.ShortcutEvent shortcutEvent = (UIShortcutsShelfItem.ShortcutEvent)event; - Node selectedNode = getShortcuts().get(shortcutEvent.Index); - - try - { - if (getPermissionService().hasPermission(selectedNode.getNodeRef(), PermissionService.READ) == AccessStatus.ALLOWED) - { - if (getNodeService().exists(selectedNode.getNodeRef()) == false) - { - throw new InvalidNodeRefException(selectedNode.getNodeRef()); - } - - DictionaryService dd = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getDictionaryService(); - if (dd.isSubClass(selectedNode.getType(), ContentModel.TYPE_FOLDER)) - { - // then navigate to the appropriate node in UI - // use browse bean functionality for this as it will update the breadcrumb for us - this.browseBean.updateUILocation(selectedNode.getNodeRef()); - } - else if (dd.isSubClass(selectedNode.getType(), ContentModel.TYPE_CONTENT)) - { - // view details for document - this.browseBean.setupContentAction(selectedNode.getId(), true); - FacesContext fc = FacesContext.getCurrentInstance(); - fc.getApplication().getNavigationHandler().handleNavigation(fc, null, "dialog:showDocDetails"); - } - } - else - { - Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), "error_shortcut_permissions")); - } - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {selectedNode.getId()}) ); - - // remove item from the shortcut list - UserTransaction tx = null; - try - { - FacesContext context = FacesContext.getCurrentInstance(); - tx = Repository.getUserTransaction(context); - tx.begin(); - - List shortcuts = getShortcutList(context); - if (shortcuts.size() > shortcutEvent.Index) - { - // remove the shortcut from the saved list and persist back - shortcuts.remove(shortcutEvent.Index); - PreferencesService.getPreferences(context).setValue(PREF_SHORTCUTS, (Serializable)shortcuts); - - // commit the transaction - tx.commit(); - - // remove shortcut Node from the in-memory list - Node node = getShortcuts().remove(shortcutEvent.Index); - - if (logger.isDebugEnabled()) - logger.debug("Removed deleted node: " + node.getName() + " from the user shortcuts list."); - } - } - catch (Throwable err) - { - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/users/UsersBeanProperties.java b/war/src/main/java/org/alfresco/web/bean/users/UsersBeanProperties.java deleted file mode 100644 index a5f9368a27..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/UsersBeanProperties.java +++ /dev/null @@ -1,495 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import java.io.Serializable; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.security.sync.UserRegistrySynchronizer; -import org.alfresco.repo.transaction.RetryingTransactionHelper; -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.service.cmr.repository.AssociationRef; -import org.alfresco.service.cmr.repository.ContentReader; -import org.alfresco.service.cmr.repository.ContentService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.search.SearchService; -import org.alfresco.service.cmr.security.MutableAuthenticationService; -import org.alfresco.service.cmr.security.PersonService; -import org.alfresco.service.cmr.usage.ContentUsageService; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.servlet.DownloadContentServlet; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.data.UIRichList; -import org.springframework.web.jsf.FacesContextUtils; - -/** - * Bean holding the properties for a Person node. - * - * Used by the Create/EditUserWizard, UsersDialog and EditUserDetailsDetails to maitain user state during dialog. - * - * Also provides access to a map of the properties to mutability which is used to disable appropriate controls on edit - * dialogs if properties are externally mapped to LDAP or similar. - */ -public class UsersBeanProperties implements Serializable -{ - private static final long serialVersionUID = 8874192805959149144L; - - /** NodeService bean reference */ - transient private NodeService nodeService; - - /** SearchService bean reference */ - transient private SearchService searchService; - - /** AuthenticationService bean reference */ - transient private MutableAuthenticationService authenticationService; - - /** PersonService bean reference */ - transient private PersonService personService; - - /** ContentUsageService bean reference */ - transient private ContentUsageService contentUsageService; - - /** userRegistrySynchronizer bean reference */ - transient private UserRegistrySynchronizer userRegistrySynchronizer; - - /** Component reference for Users RichList control */ - private UIRichList usersRichList; - - /** action context */ - private Node person = null; - private String password = null; - private String oldPassword = null; - private String confirm = null; - private String searchCriteria = null; - private String userName = null; - private Map immutabilty = null; - - - // ------------------------------------------------------------------------------ - // Bean property getters and setters - - /** - * @return the nodeService - */ - public NodeService getNodeService() - { - if (nodeService == null) - { - nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - } - return nodeService; - } - - /** - * @return the searchService - */ - public SearchService getSearchService() - { - if (searchService == null) - { - searchService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getSearchService(); - } - return searchService; - } - - /** - * @return the authenticationService - */ - public MutableAuthenticationService getAuthenticationService() - { - if (authenticationService == null) - { - authenticationService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getAuthenticationService(); - } - return authenticationService; - } - - /** - * @return the personService - */ - public PersonService getPersonService() - { - if (personService == null) - { - personService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPersonService(); - } - return personService; - } - - /** - * @return contentUsageService - */ - public ContentUsageService getContentUsageService() - { - if (contentUsageService == null) - { - contentUsageService = (ContentUsageService) FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), "ContentUsageService"); - } - return contentUsageService; - } - - /** - * @return userRegistrySynchronizer - */ - public UserRegistrySynchronizer getUserRegistrySynchronizer() - { - if (userRegistrySynchronizer == null) - { - userRegistrySynchronizer = (UserRegistrySynchronizer)FacesContextUtils.getRequiredWebApplicationContext( - FacesContext.getCurrentInstance()).getBean("userRegistrySynchronizer"); - } - return userRegistrySynchronizer; - } - - /** - * @param nodeService The NodeService to set. - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - /** - * @param searchService the search service - */ - public void setSearchService(SearchService searchService) - { - this.searchService = searchService; - } - - /** - * @param authenticationService The AuthenticationService to set. - */ - public void setAuthenticationService(MutableAuthenticationService authenticationService) - { - this.authenticationService = authenticationService; - } - - /** - * @param personService The PersonService to set. - */ - public void setPersonService(PersonService personService) - { - this.personService = personService; - } - - /** - * @param contentUsageService The ContentUsageService to set. - */ - public void setContentUsageService(ContentUsageService contentUsageService) - { - this.contentUsageService = contentUsageService; - } - - /** - * @param userRegistrySynchronizer UserRegistrySynchronizer - */ - public void setUserRegistrySynchronizer(UserRegistrySynchronizer userRegistrySynchronizer) - { - this.userRegistrySynchronizer = userRegistrySynchronizer; - } - - /** - * @return Returns the usersRichList. - */ - public UIRichList getUsersRichList() - { - return this.usersRichList; - } - - /** - * @param usersRichList The usersRichList to set. - */ - public void setUsersRichList(UIRichList usersRichList) - { - this.usersRichList = usersRichList; - } - - /** - * @return Returns the search criteria - */ - public String getSearchCriteria() - { - return searchCriteria; - } - - /** - * @param searchCriteria The search criteria to select - */ - public void setSearchCriteria(String searchCriteria) - { - this.searchCriteria = searchCriteria; - } - - /** - * @return Returns the confirm password. - */ - public String getConfirm() - { - return this.confirm; - } - - /** - * @param confirm The confirm password to set. - */ - public void setConfirm(String confirm) - { - this.confirm = confirm; - } - - /** - * @return Returns the password. - */ - public String getPassword() - { - return this.password; - } - - /** - * @param password The password to set. - */ - public void setPassword(String password) - { - this.password = password; - } - - /** - * @return Returns the old password. - */ - public String getOldPassword() - { - return this.oldPassword; - } - - /** - * @param oldPassword The old password to set. - */ - public void setOldPassword(String oldPassword) - { - this.oldPassword = oldPassword; - } - - /** - * @return Returns the person context. - */ - public Node getPerson() - { - return this.person; - } - - /** - * @param p The person context to set. - */ - public void setPerson(final Node p) - { - // perform the set in a txn as certain bean calls require it - FacesContext context = FacesContext.getCurrentInstance(); - RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(context); - RetryingTransactionCallback callback = new RetryingTransactionCallback() - { - public Object execute() throws Throwable - { - person = p; - userName = (String)person.getProperties().get(ContentModel.PROP_USERNAME); - - // rebuild the property immutability map helper object - immutabilty = new PropertyImmutabilityMap( - getUserRegistrySynchronizer().getPersonMappedProperties(userName)); - - return null; - } - }; - try - { - txnHelper.doInTransaction(callback, false); - } - catch (Throwable e) - { - // reset the flag so we can re-attempt the operation - if (e instanceof ReportedException == false) - { - Utils.addErrorMessage(e.getMessage(), e); - } - ReportedException.throwIfNecessary(e); - } - } - - public Long getUserUsage(String userName) - { - long usage = getContentUsageService().getUserUsage(userName); - return (usage == -1 ? null : usage); - } - - public Long getUserUsage() - { - long usage = getContentUsageService().getUserUsage(this.userName); - return (usage == -1 ? null : usage); - } - - public Long getUserQuota() - { - long quota = getContentUsageService().getUserQuota(this.userName); - return (quota == -1 ? null : quota); - } - - public boolean getUsagesEnabled() - { - return getContentUsageService().getEnabled(); - } - - public String getPersonDescription() - { - ContentService cs = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getContentService(); - ContentReader reader = cs.getReader(this.person.getNodeRef(), ContentModel.PROP_PERSONDESC); - if (reader != null && reader.exists()) - { - return Utils.stripUnsafeHTMLTags(reader.getContentString()).replace("\r\n", "

"); - } - else - { - return null; - } - } - - public String getAvatarUrl() - { - String avatarUrl = null; - - List refs = getNodeService().getTargetAssocs(this.person.getNodeRef(), ContentModel.ASSOC_AVATAR); - if (refs.size() == 1) - { - NodeRef photoRef = refs.get(0).getTargetRef(); - String name = (String) getNodeService().getProperty(photoRef, ContentModel.PROP_NAME); - avatarUrl = DownloadContentServlet.generateBrowserURL(photoRef, name); - } - - return avatarUrl; - } - - public Map getImmutability() - { - return this.immutabilty; - } - - /** - * Map of person property to immutability - * The Map interface is implemented to allow JSF expressions such as - * #{DialogBean.bean.properties.immutability.propertyname} - */ - public class PropertyImmutabilityMap implements Map, Serializable - { - final private Set props; - - PropertyImmutabilityMap(Set props) - { - this.props = props; - } - - public void clear() - { - } - - public boolean containsKey(Object k) - { - boolean contains = false; - if (k instanceof String && ((String)k).length() != 0) - { - String s = (String)k; - if (s.charAt(0) == '{' && s.indexOf('}') != -1) - { - contains = this.props.contains(k); - } - else - { - // simple property name - assume and apply CM namespace - contains = this.props.contains(QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, s)); - } - } - return contains; - } - - public boolean containsValue(Object v) - { - return false; - } - - public Set> entrySet() - { - return null; - } - - public Boolean get(Object k) - { - return containsKey(k); - } - - public boolean isEmpty() - { - return this.props.size() != 0; - } - - public Set keySet() - { - return null; - } - - public Boolean put(String k, Boolean v) - { - return null; - } - - public void putAll(Map m) - { - } - - public Boolean remove(Object k) - { - return null; - } - - public int size() - { - return this.props.size(); - } - - public Collection values() - { - return null; - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/users/UsersDialog.java b/war/src/main/java/org/alfresco/web/bean/users/UsersDialog.java deleted file mode 100644 index 8a697cb800..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/users/UsersDialog.java +++ /dev/null @@ -1,506 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.users; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ContentModel; -import org.alfresco.query.PagingRequest; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.security.PersonService.PersonInfo; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.IContextListener; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.dialog.ChangeViewSupport; -import org.alfresco.web.bean.repository.MapNode; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.NodePropertyResolver; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.ReportedException; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.alfresco.web.ui.common.component.UIListItem; -import org.alfresco.web.ui.common.component.UIModeList; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * @author Kevin Roast - */ -public class UsersDialog extends BaseDialogBean implements IContextListener, ChangeViewSupport -{ - private static final long serialVersionUID = 7613786955971599967L; - - private static Log logger = LogFactory.getLog(UsersDialog.class); - - public static String BEAN_NAME = "UsersDialog"; - - public static final String ERROR_PASSWORD_MATCH = "error_password_match"; - public static final String ERROR_NEGATIVE_QUOTA = "error_negative_quota"; - private static final String ERROR_DELETE = "error_delete_user"; - - private static final String DIALOG_CLOSE = "dialog:close"; - - private static final String VIEW_DETAILS = "user_details"; - private static final String LABEL_VIEW_DETAILS = "user_details"; - - /** RichList view mode */ - protected String viewMode = VIEW_DETAILS; - - protected UsersBeanProperties properties; - private List users = Collections.emptyList(); - - - // ------------------------------------------------------------------------------ - // Construction - - /** - * Default Constructor - */ - public UsersDialog() - { - UIContextService.getInstance(FacesContext.getCurrentInstance()).registerBean(this); - } - - - // ------------------------------------------------------------------------------ - // Bean property getters and setters - - /** - * @param properties the properties to set - */ - public void setProperties(UsersBeanProperties properties) - { - this.properties = properties; - } - - /** - * @return the list of user Nodes to display - */ - public List getUsers() - { - if (this.users == null) - { - search(); - } - - return this.users; - } - - public int getUsersSize() - { - return getUsers().size(); - } - - public Long getUsersTotalUsage() - { - Long totalUsage = null; - List users = getUsers(); - for(Node user : users) - { - Long sizeLatest = (Long)properties.getUserUsage((String)user.getProperties().get("userName")); - if ((sizeLatest != null) && (sizeLatest != -1L)) - { - if (totalUsage == null) { totalUsage = 0L; } - totalUsage += sizeLatest; - } - } - return totalUsage; - } - - public Long getUsersTotalQuota() - { - Long totalQuota = null; - List users = getUsers(); - for(Node user : users) - { - Long sizeCurrent = (Long)user.getProperties().get("sizeQuota"); - if ((sizeCurrent != null) && (sizeCurrent != -1L)) - { - if (totalQuota == null) { totalQuota = 0L; } - totalQuota += sizeCurrent; - } - } - return totalQuota; - } - - /** - * Action event called by all actions that need to setup a Person context on - * the Users bean before an action page is called. The context will be a - * Person Node in setPerson() which can be retrieved on the action page from - * UsersDialog.getPerson(). - */ - public void setupUserAction(ActionEvent event) - { - UIActionLink link = (UIActionLink) event.getComponent(); - Map params = link.getParameterMap(); - setupUserAction(params.get("id")); - } - - /** - * Called in preparation for actions that need to setup a Person context on - * the Users bean before an action page is called. - * - * @param personId String - */ - public void setupUserAction(String personId) - { - if (personId != null && personId.length() != 0) - { - if (logger.isDebugEnabled()) - logger.debug("Setup for action, setting current Person to: " + personId); - - try - { - // create the node ref, then our node representation - NodeRef ref = new NodeRef(Repository.getStoreRef(), personId); - Node node = new Node(ref); - - // remember the Person node - properties.setPerson(node); - - // clear the UI state in preparation for finishing the action - // and returning to the main page - contextUpdated(); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext - .getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] { personId })); - } - } - else - { - properties.setPerson(null); - } - } - - /** - * Action handler called when the OK button is clicked on the Delete User page - */ - public String deleteOK() - { - FacesContext context = FacesContext.getCurrentInstance(); - try - { - String userName = (String) properties.getPerson().getProperties().get("userName"); - - // delete the associated Person - properties.getPersonService().deletePerson(userName); - - // re-do the search to refresh the list - search(); - } - catch (Throwable e) - { - // rollback the transaction - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, - ERROR_DELETE), e.getMessage()), e); - ReportedException.throwIfNecessary(e); - } - - return DIALOG_CLOSE; - } - - /** - * Action handler called for the OK button press - */ - public String changeUserDetails() - { - String outcome = DIALOG_CLOSE; - - FacesContext context = FacesContext.getCurrentInstance(); - UserTransaction tx = null; - try - { - tx = Repository.getUserTransaction(context); - tx.begin(); - - Map props = properties.getNodeService().getProperties(properties.getPerson().getNodeRef()); - props.put(ContentModel.PROP_FIRSTNAME, - (String) properties.getPerson().getProperties().get(ContentModel.PROP_FIRSTNAME)); - props.put(ContentModel.PROP_LASTNAME, - (String) properties.getPerson().getProperties().get(ContentModel.PROP_LASTNAME)); - props.put(ContentModel.PROP_EMAIL, - (String) properties.getPerson().getProperties().get(ContentModel.PROP_EMAIL)); - - // persist changes - properties.getNodeService().setProperties(properties.getPerson().getNodeRef(), props); - - tx.commit(); - - // if the above call was successful, then reset Person Node in the session - Application.getCurrentUser(context).reset(); - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - context, Repository.ERROR_GENERIC), err.getMessage()), err ); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - - return outcome; - } - - /** - * Event handler called when the user wishes to search for a user - * - * @return The outcome - */ - public String search() - { - properties.getUsersRichList().setValue(null); - - if (properties.getSearchCriteria() == null || properties.getSearchCriteria().trim().length() == 0) - { - this.users = Collections.emptyList(); - } - else - { - FacesContext context = FacesContext.getCurrentInstance(); - UserTransaction tx = null; - - try - { - tx = Repository.getUserTransaction(context, true); - tx.begin(); - - // define the query to find people by their first or last name - String search = properties.getSearchCriteria(); - if (logger.isDebugEnabled()) - { - logger.debug("Query filter: " + search); - } - - List persons = properties.getPersonService().getPeople( - Utils.generatePersonFilter(search), - true, - Utils.generatePersonSort(), - new PagingRequest(Utils.getPersonMaxResults(), null) - ).getPage(); - - if (logger.isDebugEnabled()) - { - logger.debug("Found " + persons.size() + " users"); - } - - this.users = new ArrayList(persons.size()); - - for (PersonInfo person : persons) - { - // create our Node representation - MapNode node = new MapNode(person.getNodeRef()); - - // set data binding properties - // this will also force initialisation of the props now during the UserTransaction - // it is much better for performance to do this now rather than during page bind - Map props = node.getProperties(); - String firstName = (String)props.get("firstName"); - String lastName = (String)props.get("lastName"); - props.put("fullName", (firstName != null ? firstName : "") + ' ' + (lastName != null ? lastName : "")); - NodeRef homeFolderNodeRef = (NodeRef)props.get("homeFolder"); - if (homeFolderNodeRef != null) - { - props.put("homeSpace", homeFolderNodeRef); - } - - node.addPropertyResolver("sizeLatest", this.resolverUserSizeLatest); - node.addPropertyResolver("quota", this.resolverUserQuota); - node.addPropertyResolver("isMutable", this.resolverUserMutable); - - this.users.add(node); - } - - // commit the transaction - tx.commit(); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - context, Repository.ERROR_NODEREF), new Object[] {"root"}) ); - this.users = Collections.emptyList(); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - catch (Exception err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - context, Repository.ERROR_GENERIC), err.getMessage()), err ); - this.users = Collections.emptyList(); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - } - - // return null to stay on the same page - return null; - } - - public NodePropertyResolver resolverUserSizeLatest = new NodePropertyResolver() { - public Object get(Node personNode) { - return (Long)properties.getUserUsage((String)personNode.getProperties().get("userName")); - } - }; - - public NodePropertyResolver resolverUserQuota = new NodePropertyResolver() { - public Object get(Node personNode) { - Long quota = (Long)personNode.getProperties().get("sizeQuota"); - return (quota != null && quota != -1L) ? quota : null; - } - }; - - public NodePropertyResolver resolverUserMutable = new NodePropertyResolver() - { - public Object get(Node personNode) - { - return properties.getAuthenticationService().isAuthenticationMutable( - (String) personNode.getProperties().get("userName")); - } - }; - - /** - * Action handler to show all the users currently in the system - * - * @return The outcome - */ - public String showAll() - { - properties.getUsersRichList().setValue(null); - - this.users = Repository.getUsers(FacesContext.getCurrentInstance(), - properties.getNodeService(), properties.getPersonService()); - - for (Node node : this.users) - { - node.addPropertyResolver("sizeLatest", this.resolverUserSizeLatest); - node.addPropertyResolver("quota", this.resolverUserQuota); - node.addPropertyResolver("isMutable", this.resolverUserMutable); - } - - // return null to stay on the same page - return null; - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - return null; - } - - @Override - public String cancel() - { - contextUpdated(); - - return super.cancel(); - } - - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "close"); - } - - @Override - public Object getActionsContext() - { - return this; - } - - public List getViewItems() - { - FacesContext context = FacesContext.getCurrentInstance(); - List items = new ArrayList(1); - - UIListItem item1 = new UIListItem(); - item1.setValue(VIEW_DETAILS); - item1.setLabel(Application.getMessage(context, LABEL_VIEW_DETAILS)); - items.add(item1); - - return items; - } - - - public String getViewMode() - { - return this.viewMode; - } - - - public void setViewMode(String viewMode) - { - this.viewMode = viewMode; - } - - - public void viewModeChanged(ActionEvent event) - { - UIModeList viewList = (UIModeList)event.getComponent(); - - // update view mode from user selection - setViewMode(viewList.getValue().toString()); - } - - // ------------------------------------------------------------------------------ - // IContextListener implementation - - /** - * @see org.alfresco.web.app.context.IContextListener#contextUpdated() - */ - public void contextUpdated() - { - if (properties.getUsersRichList() != null) - { - properties.getUsersRichList().setValue(null); - this.users = null; - } - } - - /** - * @see org.alfresco.web.app.context.IContextListener#areaChanged() - */ - public void areaChanged() - { - // nothing to do - } - - /** - * @see org.alfresco.web.app.context.IContextListener#spaceChanged() - */ - public void spaceChanged() - { - // nothing to do - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/wizard/AbstractWizardBean.java b/war/src/main/java/org/alfresco/web/bean/wizard/AbstractWizardBean.java deleted file mode 100644 index 1ae824a5bb..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/wizard/AbstractWizardBean.java +++ /dev/null @@ -1,359 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.wizard; - -import java.io.Serializable; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.service.cmr.model.FileFolderService; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.search.SearchService; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.bean.BrowseBean; -import org.alfresco.web.bean.NavigationBean; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.Utils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Abstract bean used as the base class for all wizard backing beans. - * - * @author gavinc - */ -public abstract class AbstractWizardBean implements Serializable -{ - private static Log logger = LogFactory.getLog(AbstractWizardBean.class); - - /** I18N messages */ - private static final String MSG_NOT_SET = "value_not_set"; - - protected static final String FINISH_OUTCOME = "finish"; - protected static final String CANCEL_OUTCOME = "cancel"; - protected static final String DEFAULT_INSTRUCTION_ID = "default_instruction"; - protected static final String SUMMARY_TITLE_ID = "summary"; - protected static final String SUMMARY_DESCRIPTION_ID = "summary_desc"; - - // common wizard properties - protected int currentStep = 1; - protected boolean editMode = false; - transient private NodeService nodeService; - transient private FileFolderService fileFolderService; - transient private SearchService searchService; - protected NavigationBean navigator; - protected BrowseBean browseBean; - - /** - * @return Returns the wizard description - */ - public abstract String getWizardDescription(); - - /** - * @return Returns the wizard title - */ - public abstract String getWizardTitle(); - - /** - * @return Returns the title for the current step - */ - public abstract String getStepTitle(); - - /** - * @return Returns the description for the current step - */ - public abstract String getStepDescription(); - - /** - * @return Returns the instructional text for the current step - */ - public abstract String getStepInstructions(); - - /** - * Determines the outcome string for the given step number - * - * @param step The step number to get the outcome for - * @return The outcome - */ - protected abstract String determineOutcomeForStep(int step); - - /** - * Handles the finish button being pressed - * - * @return The finish outcome - */ - public abstract String finish(); - - /** - * Action listener called when the wizard is being launched allowing - * state to be setup - */ - public void startWizard(ActionEvent event) - { - // refresh the UI, calling this method now is fine as it basically makes sure certain - // beans clear the state - so when we finish the wizard other beans will have been reset - UIContextService.getInstance(FacesContext.getCurrentInstance()).notifyBeans(); - - // make sure the wizard is not in edit mode - this.editMode = false; - - // initialise the wizard in case we are launching - // after it was navigated away from - init(); - - if (logger.isDebugEnabled()) - logger.debug("Started wizard : " + getWizardTitle()); - } - - /** - * Action listener called when the wizard is being launched for - * editing an existing node. - */ - public void startWizardForEdit(ActionEvent event) - { - // refresh the UI, calling this method now is fine as it basically makes sure certain - // beans clear the state - so when we finish the wizard other beans will have been reset - UIContextService.getInstance(FacesContext.getCurrentInstance()).notifyBeans(); - - // set the wizard in edit mode - this.editMode = true; - - // populate the wizard's default values with the current value - // from the node being edited - init(); - populate(); - - if (logger.isDebugEnabled()) - logger.debug("Started wizard : " + getWizardTitle() + " for editing"); - } - - /** - * Determines whether the wizard is in edit mode - * - * @return true if the wizard is in edit mode, false if it is in creation mode - */ - public boolean isInEditMode() - { - return this.editMode; - } - - /** - * Deals with the next button being pressed - * - * @return The outcome for the next step - */ - public String next() - { - this.currentStep++; - - // determine which page to go to next - String outcome = determineOutcomeForStep(this.currentStep); - - if (logger.isDebugEnabled()) - { - logger.debug("current step is now: " + this.currentStep); - logger.debug("Next outcome: " + outcome); - } - - // return the outcome for navigation - return outcome; - } - - /** - * Deals with the back button being pressed - * - * @return The outcome for the previous step - */ - public String back() - { - this.currentStep--; - - // determine which page to go to next - String outcome = determineOutcomeForStep(this.currentStep); - - if (logger.isDebugEnabled()) - { - logger.debug("current step is now: " + this.currentStep); - logger.debug("Back outcome: " + outcome); - } - - // return the outcome for navigation - return outcome; - } - - /** - * Handles the cancelling of the wizard - * - * @return The cancel outcome - */ - public String cancel() - { - // reset the state - init(); - - return CANCEL_OUTCOME; - } - - /** - * Initialises the wizard - */ - public void init() - { - this.currentStep = 1; - } - - /** - * Populates the wizard's values with the current values - * of the node about to be edited - */ - public void populate() - { - // subclasses will override this method to setup accordingly - } - - /** - * @return Returns the nodeService. - */ - public NodeService getNodeService() - { - if (nodeService == null) - { - nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - } - return this.nodeService; - } - - /** - * @param nodeService The nodeService to set. - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - /** - * @param fileFolderService used to manipulate folder/folder model nodes - */ - public void setFileFolderService(FileFolderService fileFolderService) - { - this.fileFolderService = fileFolderService; - } - - protected FileFolderService getFileFolderService() - { - if (fileFolderService == null) - { - fileFolderService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getFileFolderService(); - } - return fileFolderService; - } - - /** - * @param searchService the service used to find nodes - */ - public void setSearchService(SearchService searchService) - { - this.searchService = searchService; - } - - protected SearchService getSearchService() - { - if (searchService == null) - { - searchService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getSearchService(); - } - return searchService; - } - - /** - * @return Returns the navigation bean instance. - */ - public NavigationBean getNavigator() - { - return navigator; - } - - /** - * @param navigator The NavigationBean to set. - */ - public void setNavigator(NavigationBean navigator) - { - this.navigator = navigator; - } - - /** - * @return The BrowseBean - */ - public BrowseBean getBrowseBean() - { - return this.browseBean; - } - - /** - * @param browseBean The BrowseBean to set. - */ - public void setBrowseBean(BrowseBean browseBean) - { - this.browseBean = browseBean; - } - - /** - * Build summary table from the specified list of Labels and Values - * - * @param labels Array of labels to display - * @param values Array of values to display - * - * @return summary table HTML - */ - protected String buildSummary(String[] labels, String[] values) - { - if (labels == null || values == null || labels.length != values.length) - { - throw new IllegalArgumentException("Labels and Values passed to summary must be valid and of equal length."); - } - - String msg = Application.getMessage(FacesContext.getCurrentInstance(), MSG_NOT_SET); - String notSetMsg = "<" + msg + ">"; - - StringBuilder buf = new StringBuilder(256); - - buf.append(""); - for (int i=0; i"); - } - buf.append("
"); - buf.append(labels[i]); - buf.append(":"); - buf.append(value != null ? Utils.encode(value) : notSetMsg); - buf.append("
"); - - return buf.toString(); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/wizard/BaseInviteUsersWizard.java b/war/src/main/java/org/alfresco/web/bean/wizard/BaseInviteUsersWizard.java deleted file mode 100644 index 1d05f3d47b..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/wizard/BaseInviteUsersWizard.java +++ /dev/null @@ -1,909 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.wizard; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.ResourceBundle; -import java.util.Set; -import java.util.TreeSet; - -import javax.faces.component.UISelectOne; -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.faces.model.DataModel; -import javax.faces.model.ListDataModel; -import javax.faces.model.SelectItem; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ContentModel; -import org.alfresco.query.PagingRequest; -import org.alfresco.query.PagingResults; -import org.alfresco.repo.security.permissions.AccessDeniedException; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.security.AuthorityService; -import org.alfresco.service.cmr.security.AuthorityType; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.cmr.security.PersonService; -import org.alfresco.service.cmr.security.PersonService.PersonInfo; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.util.Pair; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.TemplateMailHelperBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.repository.User; -import org.alfresco.web.data.IDataContainer; -import org.alfresco.web.data.QuickSort; -import org.alfresco.web.ui.common.SortableSelectItem; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIGenericPicker; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.lucene.search.BooleanQuery; -import org.springframework.mail.javamail.JavaMailSender; - -/** - * Backing bean for the Invite Users wizard(s) - * - * @author Kevin Roast - */ -public abstract class BaseInviteUsersWizard extends BaseWizardBean -{ - private static final long serialVersionUID = -5145813383038390250L; - - private final static Log logger = LogFactory.getLog(BaseInviteUsersWizard.class); - - /** I18N message strings */ - protected static final String MSG_USERROLES = "invite_users_summary"; - private static final String MSG_USERS = "users"; - private static final String MSG_GROUPS = "groups"; - private static final String MSG_INVITED_TO = "invited_to"; - private static final String MSG_INVITED_ROLE = "invite_role"; - private static final String MSG_MAX_USERS = "max_users_returned"; - private static final String MSG_SEARCH_MINIMUM = "picker_search_min"; - - protected static final String STEP_NOTIFY = "notify"; - - private static final String NOTIFY_YES = "yes"; - private static final String NOTIFY_NO = "no"; - - /** NamespaceService bean reference */ - transient private NamespaceService namespaceService; - - /** JavaMailSender bean reference */ - transient private JavaMailSender mailSender; - - /** AuthorityService bean reference */ - transient private AuthorityService authorityService; - - /** PermissionService bean reference */ - transient protected PermissionService permissionService; - - /** personService bean reference */ - transient private PersonService personService; - - /** Helper providing template based mailing facilities */ - protected TemplateMailHelperBean mailHelper; - - /** datamodel for table of roles for users */ - transient private DataModel userRolesDataModel = null; - - /** list of user/group role wrapper objects */ - protected List userGroupRoles = null; - - /** True to allow duplicate authorities (with a different role) */ - protected boolean allowDuplicateAuthorities = true; - - /** Flag to determine if the maximum number of users have been returned */ - protected boolean maxUsersReturned = false; - - /** dialog state */ - private String notify = NOTIFY_NO; - - /** - * @return a cached list of available permissions for the type being dealt with - */ - protected abstract Set getPermissionsForType(); - - /** - * @return Returns the node that the permissions are being applied to - */ - protected abstract Node getNode(); - - /** - * @return Returns the list of email templates for user notification - */ - public List getEmailTemplates() - { - List wrappers = null; - - try - { - FacesContext fc = FacesContext.getCurrentInstance(); - NodeRef rootNodeRef = this.getNodeService().getRootNode(Repository.getStoreRef()); - NamespaceService resolver = Repository.getServiceRegistry(fc).getNamespaceService(); - List results = this.getSearchService().selectNodes(rootNodeRef, getEmailTemplateXPath(), null, resolver, false); - - wrappers = new ArrayList(results.size() + 1); - if (results.size() != 0) - { - DictionaryService dd = Repository.getServiceRegistry(fc).getDictionaryService(); - for (NodeRef ref : results) - { - if (this.getNodeService().exists(ref) == true) - { - Node childNode = new Node(ref); - if (dd.isSubClass(childNode.getType(), ContentModel.TYPE_CONTENT)) - { - wrappers.add(new SelectItem(childNode.getId(), childNode.getName())); - } - } - } - - // make sure the list is sorted by the label - QuickSort sorter = new QuickSort(wrappers, "label", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - } - } - catch (AccessDeniedException accessErr) - { - // ignore the result if we cannot access the root - } - - // add an entry (at the start) to instruct the user to select an item - if (wrappers == null) - { - wrappers = new ArrayList(1); - } - wrappers.add(0, new SelectItem("none", Application.getMessage(FacesContext.getCurrentInstance(), "select_a_template"))); - - return wrappers; - } - - protected abstract String getEmailTemplateXPath(); - - /** - * @param namespaceService The NamespaceService to set. - */ - public void setNamespaceService(NamespaceService namespaceService) - { - this.namespaceService = namespaceService; - } - - protected NamespaceService getNamespaceService() - { - if (namespaceService == null) - { - namespaceService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNamespaceService(); - } - return namespaceService; - } - - /** - * @param mailSender The JavaMailSender to set. - */ - public void setMailSender(JavaMailSender mailSender) - { - this.mailSender = mailSender; - } - - /** - * @param permissionService The PermissionService to set. - */ - public void setPermissionService(PermissionService permissionService) - { - this.permissionService = permissionService; - } - - protected PermissionService getPermissionService() - { - if (permissionService == null) - { - permissionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPermissionService(); - } - return permissionService; - } - - /** - * @param personService The PersonService to set. - */ - public void setPersonService(PersonService personService) - { - this.personService = personService; - } - - protected PersonService getPersonService() - { - if (personService == null) - { - personService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPersonService(); - } - return personService; - } - - /** - * @param authorityService The authorityService to set. - */ - public void setAuthorityService(AuthorityService authorityService) - { - this.authorityService = authorityService; - } - - protected AuthorityService getAuthorityService() - { - if (authorityService == null) - { - authorityService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getAuthorityService(); - } - return authorityService; - } - - /** - * Initialises the wizard - */ - @Override - public void init(Map parameters) - { - super.init(parameters); - - maxUsersReturned = false; - notify = NOTIFY_NO; - userRolesDataModel = null; - userGroupRoles = new ArrayList(8); - mailHelper = new TemplateMailHelperBean(); - mailHelper.setMailSender(mailSender); - mailHelper.setNodeService(getNodeService()); - } - - /** - * @see org.alfresco.web.bean.dialog.BaseDialogBean#finishImpl(javax.faces.context.FacesContext, java.lang.String) - */ - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - User user = Application.getCurrentUser(context); - String from = (String)this.getNodeService().getProperty(user.getPerson(), ContentModel.PROP_EMAIL); - if (from == null || from.length() == 0) - { - // if the user does not have an email address get the default one from the config service - from = Application.getClientConfig(context).getFromEmailAddress(); - } - - // get the Space to apply changes too - NodeRef nodeRef = this.getNode().getNodeRef(); - - // set permissions for each user and send them a mail - for (int i=0; i perms = getPermissionsForType(); - for (String permission : perms) - { - if (userGroupRole.getRole().equals(permission)) - { - this.getPermissionService().setPermission( - nodeRef, - authority, - permission, - true); - break; - } - } - - // Create the mail message for sending to each User - if (NOTIFY_YES.equals(this.notify)) - { - // if User, email then, else if Group get all members and email them - AuthorityType authType = AuthorityType.getAuthorityType(authority); - if (authType.equals(AuthorityType.USER)) - { - if (this.getPersonService().personExists(authority) == true) - { - this.mailHelper.notifyUser( - this.getPersonService().getPerson(authority), nodeRef, from, userGroupRole.getRole()); - } - } - else if (authType.equals(AuthorityType.GROUP)) - { - // else notify all members of the group - Set users = this.getAuthorityService().getContainedAuthorities(AuthorityType.USER, authority, false); - for (String userAuth : users) - { - if (this.getPersonService().personExists(userAuth) == true) - { - this.mailHelper.notifyUser( - this.getPersonService().getPerson(userAuth), nodeRef, from, userGroupRole.getRole()); - } - } - } - } - } - - // reset max users flag - this.maxUsersReturned = false; - - return outcome; - } - - /* (non-Javadoc) - * @see org.alfresco.web.bean.dialog.BaseDialogBean#cancel() - */ - @Override - public String cancel() - { - // reset max users flag - this.maxUsersReturned = false; - - return super.cancel(); - } - - /** - * @see org.alfresco.web.bean.dialog.BaseDialogBean#getFinishButtonDisabled() - */ - @Override - public boolean getFinishButtonDisabled() - { - boolean disabled = true; - - String stepName = Application.getWizardManager().getCurrentStepName(); - if (STEP_NOTIFY.equals(stepName)) - { - disabled = false; - } - - return disabled; - } - - /** - * Returns the properties for current user-roles JSF DataModel - * - * @return JSF DataModel representing the current user-roles - */ - public DataModel getUserRolesDataModel() - { - if (this.userRolesDataModel == null) - { - this.userRolesDataModel = new ListDataModel(); - } - - // only set the wrapped data once otherwise the rowindex is reset - if (this.userRolesDataModel.getWrappedData() == null) - { - this.userRolesDataModel.setWrappedData(this.userGroupRoles); - } - - return this.userRolesDataModel; - } - - /** - * Query callback method executed by the Generic Picker component. - * This method is part of the contract to the Generic Picker, it is up to the backing bean - * to execute whatever query is appropriate and return the results. - * - * @param filterIndex Index of the filter drop-down selection - * @param contains Text from the contains textbox - * - * @return An array of SelectItem objects containing the results to display in the picker. - */ - public SelectItem[] pickerCallback(int filterIndex, String contains) - { - FacesContext context = FacesContext.getCurrentInstance(); - - // quick exit if not enough characters entered for a search - String search = contains.trim(); - int searchMin = Application.getClientConfig(context).getPickerSearchMinimum(); - if (search.length() < searchMin) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, MSG_SEARCH_MINIMUM), searchMin)); - return new SelectItem[0]; - } - - SelectItem[] items; - this.maxUsersReturned = false; - - UserTransaction tx = null; - try - { - tx = Repository.getUserTransaction(context, true); - tx.begin(); - - int maxResults = Application.getClientConfig(context).getInviteUsersMaxResults(); - if(maxResults <=0) - { - maxResults = Utils.getPersonMaxResults(); - } - - List results; - - if (filterIndex == 0) - { - // Use lucene search to retrieve user details - List> filter = null; - if (search == null || search.length() == 0) - { - // if there is no search term, search for all people - } - else - { - filter = Utils.generatePersonFilter(search); - } - - if (logger.isDebugEnabled()) - { - logger.debug("Maximum invite users results size: " + maxResults); - logger.debug("Using query filter to find users: " + filter); - } - - List persons = getPersonService().getPeople( - filter, - true, - Utils.generatePersonSort(), - new PagingRequest(maxResults, null) - ).getPage(); - - results = new ArrayList(persons.size()); - for (int index=0; index addGroupItems(String search, int maxResults) - { - Set groups = getGroups(search); - - List results = new ArrayList(groups.size()); - - int count = 0; - String groupDisplayName; - for (String group : groups) - { - // get display name, if not present strip prefix from group id - groupDisplayName = getAuthorityService().getAuthorityDisplayName(group); - if (groupDisplayName == null || groupDisplayName.length() == 0) - { - groupDisplayName = group.substring(PermissionService.GROUP_PREFIX.length()); - } - - results.add(new SortableSelectItem(group, groupDisplayName, groupDisplayName)); - - if (++count == maxResults) break; - } - return results; - } - - protected Set getGroups(String search) - { - return getGroups(search, true); - } - - protected Set getGroups(String search, boolean includeEveryone) - { - Set groups; - - if (search != null && search.startsWith("*")) - { - // if the search term starts with a wildcard use Lucene based search to find groups (results will be inconsistent) - String term = search.trim() + "*"; - groups = getAuthorityService().findAuthorities(AuthorityType.GROUP, null, false, term, - AuthorityService.ZONE_APP_DEFAULT); - } - else - { - // all other searches use the canned query so search results are consistent - PagingResults pagedResults = getAuthorityService().getAuthorities(AuthorityType.GROUP, - AuthorityService.ZONE_APP_DEFAULT, search, true, true, new PagingRequest(10000)); - groups = new LinkedHashSet(pagedResults.getPage()); - } - - if (includeEveryone) - { - // add the EVERYONE group to the results - groups.addAll(getAuthorityService().getAllAuthorities(AuthorityType.EVERYONE)); - } - - return groups; - } - - /** - * Action handler called when the Add button is pressed to process the current selection - */ - public void addSelection(ActionEvent event) - { - UIGenericPicker picker = (UIGenericPicker)event.getComponent().findComponent("picker"); - UISelectOne rolePicker = (UISelectOne)event.getComponent().findComponent("roles"); - - String[] results = picker.getSelectedResults(); - if (results != null) - { - String role = (String)rolePicker.getValue(); - if (role != null) - { - for (int i=0; i perms = getPermissionsForType(); - SelectItem[] roles = new SelectItem[perms.size()]; - int index = 0; - for (String permission : perms) - { - String displayLabel = bundle.getString(permission); - if (displayLabel.startsWith("$$") == true) - { - displayLabel = permission; - } - roles[index++] = new SelectItem(permission, displayLabel); - } - - return roles; - } - - /** - * @return Returns the notify listbox selection. - */ - public String getNotify() - { - return this.notify; - } - - /** - * @param notify The notify listbox selection to set. - */ - public void setNotify(String notify) - { - this.notify = notify; - } - - @Override - public String next() - { - String stepName = Application.getWizardManager().getCurrentStepName(); - - if (STEP_NOTIFY.equals(stepName)) - { - FacesContext context = FacesContext.getCurrentInstance(); - - // prepare automatic text for email and display - StringBuilder buf = new StringBuilder(256); - - String personName = Application.getCurrentUser(context).getFullName(this.getNodeService()); - String msgInvitedTo = Application.getMessage(context, MSG_INVITED_TO); - Node node = this.getNode(); - String path = this.getNodeService().getPath(node.getNodeRef()).toDisplayPath( - this.getNodeService(), getPermissionService()); - buf.append(MessageFormat.format(msgInvitedTo, new Object[] { - path + '/' + node.getName(), - personName}) ); - - // default the subject line to an informative message - this.mailHelper.setSubject(buf.toString()); - - // add the rest of the automatic body text - buf.append("\r\n\r\n"); - - String msgRole = Application.getMessage(context, MSG_INVITED_ROLE); - String roleText; - if (this.userGroupRoles.size() != 0) - { - String roleMsg = Application.getMessage(context, userGroupRoles.get(0).getRole()); - roleText = MessageFormat.format(msgRole, roleMsg); - } - else - { - roleText = MessageFormat.format(msgRole, "[role]"); - } - - buf.append(roleText); - - // set the body content and default text to this text - this.mailHelper.setAutomaticText(buf.toString()); - this.mailHelper.setBody(this.mailHelper.getAutomaticText()); - } - - return null; - } - - /** - * @return TemplateMailHelperBean instance for this wizard - */ - public TemplateMailHelperBean getMailHelper() - { - return this.mailHelper; - } - - /** - * Helper to build a label of the form: - * Firstname Lastname (Role) - */ - public String buildLabelForUserAuthorityRole(String authority, String role) - { - // found a User authority - NodeRef ref = this.getPersonService().getPerson(authority); - String firstName = (String)this.getNodeService().getProperty(ref, ContentModel.PROP_FIRSTNAME); - String lastName = (String)this.getNodeService().getProperty(ref, ContentModel.PROP_LASTNAME); - - StringBuilder buf = new StringBuilder(100); - buf.append(firstName != null ? firstName : "") - .append(" ") - .append(lastName != null ? lastName : "") - .append(" (") - .append(Application.getMessage(FacesContext.getCurrentInstance(), role)) - .append(")"); - - return buf.toString(); - } - - /** - * Helper to build a label for a Group authority of the form: - * Groupname (role) - */ - public String buildLabelForGroupAuthorityRole(String authority, String role) - { - String groupDisplayName = this.authorityService.getAuthorityDisplayName(authority); - if (groupDisplayName == null || groupDisplayName.length() == 0) - { - groupDisplayName = authority.substring(PermissionService.GROUP_PREFIX.length()); - } - - StringBuilder buf = new StringBuilder(100); - buf.append(groupDisplayName) - .append(" (") - .append(Application.getMessage(FacesContext.getCurrentInstance(), role)) - .append(")"); - - return buf.toString(); - } - - /** - * @return summary text for the wizard - */ - public String getSummary() - { - FacesContext fc = FacesContext.getCurrentInstance(); - - // build a summary section to list the invited users and there roles - StringBuilder buf = new StringBuilder(128); - for (UserGroupRole userRole : this.userGroupRoles) - { - buf.append(Utils.encode(userRole.getLabel())); - buf.append("
"); - } - - return buildSummary( - new String[] {Application.getMessage(fc, MSG_USERROLES)}, - new String[] {buf.toString()}); - } - - /** - * @return flag to indicate whether maximum users have been returned - */ - public boolean getHaveMaximumUsersBeenReturned() - { - return this.maxUsersReturned; - } - - /** - * @return Message to display when the maximum number of users have been returned - */ - public String getMaximumUsersMsg() - { - FacesContext context = FacesContext.getCurrentInstance(); - - String pattern = Application.getMessage(context, MSG_MAX_USERS); - String msg = MessageFormat.format(pattern, - Application.getClientConfig(context).getInviteUsersMaxResults()); - - return Utils.encode(msg); - } - - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException - { - in.defaultReadObject(); - - this.userRolesDataModel = new ListDataModel(); - this.userRolesDataModel.setWrappedData(this.userGroupRoles); - - } - - /** - * Simple wrapper class to represent a user/group and a role combination - */ - public static class UserGroupRole implements Serializable - { - private static final long serialVersionUID = -3200146057437311225L; - - public UserGroupRole(String authority, String role, String label) - { - this.authority = authority; - this.role = role; - this.label = label; - } - - public String getAuthority() - { - return this.authority; - } - - public String getRole() - { - return this.role; - } - - public String getLabel() - { - return this.label; - } - - private String authority; - private String role; - private String label; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/wizard/BaseWizardBean.java b/war/src/main/java/org/alfresco/web/bean/wizard/BaseWizardBean.java deleted file mode 100644 index 5f67ad2048..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/wizard/BaseWizardBean.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.wizard; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.ui.common.Utils; - -/** - * Base class for all wizard beans providing common functionality - * - * @author gavinc - */ -public abstract class BaseWizardBean extends BaseDialogBean implements IWizardBean -{ - private static final String MSG_NOT_SET = "value_not_set"; - - public String next() - { - if (isFinished()) - { - Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), - "error_wizard_completed_already")); - } - - return null; - } - - public String back() - { - if (isFinished()) - { - Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), - "error_wizard_completed_already")); - } - - return null; - } - - public boolean getNextButtonDisabled() - { - return false; - } - - public String getNextButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "next_button"); - } - - public String getBackButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "back_button"); - } - - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "finish_button"); - } - - public String getStepTitle() - { - return null; - } - - public String getStepDescription() - { - return null; - } - - /** - * Build summary table from the specified list of Labels and Values - * - * @param labels Array of labels to display - * @param values Array of values to display - * - * @return summary table HTML - */ - protected String buildSummary(String[] labels, String[] values) - { - if (labels == null || values == null || labels.length != values.length) - { - throw new IllegalArgumentException("Labels and Values passed to summary must be valid and of equal length."); - } - - String msg = Application.getMessage(FacesContext.getCurrentInstance(), MSG_NOT_SET); - String notSetMsg = "<" + msg + ">"; - - StringBuilder buf = new StringBuilder(512); - - buf.append(""); - for (int i=0; i"); - } - buf.append("
"); - buf.append(labels[i]); - buf.append(":"); - buf.append(value != null ? value : notSetMsg); - buf.append("
"); - - return buf.toString(); - } - - @Override - protected String getDefaultCancelOutcome() - { - return AlfrescoNavigationHandler.CLOSE_WIZARD_OUTCOME; - } - - @Override - protected String getDefaultFinishOutcome() - { - return AlfrescoNavigationHandler.CLOSE_WIZARD_OUTCOME; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/wizard/IWizardBean.java b/war/src/main/java/org/alfresco/web/bean/wizard/IWizardBean.java deleted file mode 100644 index f8b37c860b..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/wizard/IWizardBean.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.wizard; - -import org.alfresco.web.bean.dialog.IDialogBean; - -/** - * Interface that defines the contract for a wizard backing bean - * - * @author gavinc - */ -public interface IWizardBean extends IDialogBean -{ - /** - * Called when the next button is pressed by the user - * - * @return Reserved for future use - */ - public String next(); - - /** - * Called when the back button is pressed by the user - * - * @return Reserved for future use - */ - public String back(); - - /** - * Returns the label to use for the next button - * - * @return The next button label - */ - public String getNextButtonLabel(); - - /** - * Returns the label to use for the back button - * - * @return The back button label - */ - public String getBackButtonLabel(); - - /** - * Determines whether the next button on the wizard should be disabled - * - * @return true if the button should be disabled - */ - public boolean getNextButtonDisabled(); - - /** - * Returns the title to be used for the current step - *

If this returns null the WizardManager will - * lookup the title via the dialog configuration

- * - * @return The title or null if the title is to be acquired via configuration - */ - public String getStepTitle(); - - /** - * Returns the description to be used for the current step - *

If this returns null the WizardManager will - * lookup the description via the dialog configuration

- * - * @return The decsription or null if the title is to be acquired via configuration - */ - public String getStepDescription(); -} diff --git a/war/src/main/java/org/alfresco/web/bean/wizard/NewUserWizard.java b/war/src/main/java/org/alfresco/web/bean/wizard/NewUserWizard.java deleted file mode 100644 index 97a3b9e4f8..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/wizard/NewUserWizard.java +++ /dev/null @@ -1,1094 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.wizard; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.ResourceBundle; - -import javax.faces.application.FacesMessage; -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.faces.validator.ValidatorException; -import javax.transaction.UserTransaction; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.security.authentication.AuthenticationException; -import org.alfresco.repo.tenant.TenantService; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.security.MutableAuthenticationService; -import org.alfresco.service.cmr.security.OwnableService; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.cmr.security.PersonService; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.context.UIContextService; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.spaces.CreateSpaceWizard; -import org.alfresco.web.bean.users.UsersDialog; -import org.alfresco.web.config.ClientConfigElement; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.validator.EmailValidator; - -/** - * @deprecated Replaced by CreateUserWizard. - * @author Kevin Roast - */ -public class NewUserWizard extends AbstractWizardBean -{ - private static final long serialVersionUID = -4608152661068880638L; - - private static Log logger = LogFactory.getLog(NewUserWizard.class); - - private static final String WIZARD_TITLE_NEW_ID = "new_user_title"; - private static final String WIZARD_DESC_NEW_ID = "new_user_desc"; - private static final String WIZARD_TITLE_EDIT_ID = "new_user_title_edit"; - private static final String WIZARD_DESC_EDIT_ID = "new_user_desc_edit"; - private static final String STEP1_TITLE_ID = "new_user_step1_title"; - private static final String STEP1_DESCRIPTION_ID = "new_user_step1_desc"; - private static final String STEP2_TITLE_ID = "new_user_step2_title"; - private static final String STEP2_DESCRIPTION_ID = "new_user_step2_desc"; - private static final String FINISH_INSTRUCTION_ID = "new_user_finish_instruction"; - private static final String ERROR = "error_person"; - private static final String MSG_ERROR_MAIL_NOT_VALID = "email_format_is_not_valid"; - - /** form variables */ - private String firstName = null; - private String lastName = null; - private String userName = null; - private String password = null; - private String confirm = null; - private String email = null; - private String companyId = null; - private String homeSpaceName = ""; - private NodeRef homeSpaceLocation = null; - - /** AuthenticationService bean reference */ - transient private MutableAuthenticationService authenticationService; - - /** NamespaceService bean reference */ - transient private NamespaceService namespaceService; - - /** PermissionService bean reference */ - transient private PermissionService permissionService; - - /** PersonService bean reference */ - transient private PersonService personService; - - /** TenantService bean reference */ - private TenantService tenantService; - - /** OwnableService bean reference */ - transient private OwnableService ownableService; - - /** action context */ - private Node person = null; - - /** ref to the default home location */ - private NodeRef defaultHomeSpaceRef; - - /** ref to the company home space folder */ - private NodeRef companyHomeSpaceRef = null; - - - /** - * @param authenticationService The AuthenticationService to set. - */ - public void setAuthenticationService(MutableAuthenticationService authenticationService) - { - this.authenticationService = authenticationService; - } - - private MutableAuthenticationService getAuthenticationService() - { - if (authenticationService == null) - { - authenticationService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getAuthenticationService(); - } - return authenticationService; - } - - /** - * @param namespaceService The namespaceService to set. - */ - public void setNamespaceService(NamespaceService namespaceService) - { - this.namespaceService = namespaceService; - } - - private NamespaceService getNamespaceService() - { - if (namespaceService == null) - { - namespaceService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNamespaceService(); - } - return namespaceService; - } - - /** - * @param permissionService The PermissionService to set. - */ - public void setPermissionService(PermissionService permissionService) - { - this.permissionService = permissionService; - } - - private PermissionService getPermissionService() - { - if (permissionService == null) - { - permissionService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPermissionService(); - } - return permissionService; - } - - /** - * @param personService The person service. - */ - public void setPersonService(PersonService personService) - { - this.personService = personService; - } - - private PersonService getPersonService() - { - if (personService == null) - { - personService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPersonService(); - } - return personService; - } - - /** - * @param ownableService The ownableService to set. - */ - public void setOwnableService(OwnableService ownableService) - { - this.ownableService = ownableService; - } - - private OwnableService getOwnableService() - { - if (ownableService == null) - { - ownableService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getOwnableService(); - } - return ownableService; - } - - /** - * @param tenantService The tenantService to set. - */ - public void setTenantService(TenantService tenantService) - { - this.tenantService = tenantService; - } - - /** - * Initialises the wizard - */ - public void init() - { - super.init(); - - // reset all variables - this.firstName = ""; - this.lastName = ""; - this.userName = ""; - this.password = ""; - this.confirm = ""; - this.email = ""; - this.companyId = ""; - this.homeSpaceName = ""; - this.homeSpaceLocation = getDefaultHomeSpace(); - } - - /** - * @see org.alfresco.web.bean.wizard.AbstractWizardBean#populate() - */ - public void populate() - { - // set values for edit mode - Map props = getPerson().getProperties(); - - this.firstName = (String) props.get("firstName"); - this.lastName = (String) props.get("lastName"); - this.userName = (String) props.get("userName"); - this.password = ""; - this.confirm = ""; - this.email = (String) props.get("email"); - this.companyId = (String) props.get("organizationId"); - - // calculate home space name and parent space Id from homeFolderId - this.homeSpaceLocation = null; // default to Company root space - this.homeSpaceName = ""; // default to none set below root - NodeRef homeFolderRef = (NodeRef) props.get("homeFolder"); - if (homeFolderRef != null && this.getNodeService().exists(homeFolderRef) == true) - { - ChildAssociationRef childAssocRef = this.getNodeService().getPrimaryParent(homeFolderRef); - NodeRef parentRef = childAssocRef.getParentRef(); - if (this.getNodeService().getRootNode(Repository.getStoreRef()).equals(parentRef) == false) - { - this.homeSpaceLocation = parentRef; - this.homeSpaceName = Repository.getNameForNode(getNodeService(), homeFolderRef); - } - else - { - this.homeSpaceLocation = homeFolderRef; - } - } - - if (logger.isDebugEnabled()) - logger.debug("Edit user home space location: " + homeSpaceLocation + " home space name: " + homeSpaceName); - } - - /** - * @see org.alfresco.web.bean.wizard.AbstractWizardBean#getWizardDescription() - */ - public String getWizardDescription() - { - if (this.editMode) - { - return Application.getMessage(FacesContext.getCurrentInstance(), WIZARD_DESC_EDIT_ID); - } - else - { - return Application.getMessage(FacesContext.getCurrentInstance(), WIZARD_DESC_NEW_ID); - } - } - - /** - * @see org.alfresco.web.bean.wizard.AbstractWizardBean#getWizardTitle() - */ - public String getWizardTitle() - { - if (this.editMode) - { - return Application.getMessage(FacesContext.getCurrentInstance(), WIZARD_TITLE_EDIT_ID); - } - else - { - return Application.getMessage(FacesContext.getCurrentInstance(), WIZARD_TITLE_NEW_ID); - } - } - - /** - * @see org.alfresco.web.bean.wizard.AbstractWizardBean#getStepTitle() - */ - public String getStepTitle() - { - String stepTitle = null; - - switch (this.currentStep) - { - case 1: - { - stepTitle = Application.getMessage(FacesContext.getCurrentInstance(), STEP1_TITLE_ID); - break; - } - case 2: - { - stepTitle = Application.getMessage(FacesContext.getCurrentInstance(), STEP2_TITLE_ID); - break; - } - case 3: - { - stepTitle = Application.getMessage(FacesContext.getCurrentInstance(), SUMMARY_TITLE_ID); - break; - } - default: - { - stepTitle = ""; - } - } - - return stepTitle; - } - - /** - * @see org.alfresco.web.bean.wizard.AbstractWizardBean#getStepDescription() - */ - public String getStepDescription() - { - String stepDesc = null; - - switch (this.currentStep) - { - case 1: - { - stepDesc = Application.getMessage(FacesContext.getCurrentInstance(), STEP1_DESCRIPTION_ID); - break; - } - case 2: - { - stepDesc = Application.getMessage(FacesContext.getCurrentInstance(), STEP2_DESCRIPTION_ID); - break; - } - case 3: - { - stepDesc = Application.getMessage(FacesContext.getCurrentInstance(), SUMMARY_DESCRIPTION_ID); - break; - } - default: - { - stepDesc = ""; - } - } - - return stepDesc; - } - - /** - * @see org.alfresco.web.bean.wizard.AbstractWizardBean#getStepInstructions() - */ - public String getStepInstructions() - { - String stepInstruction = null; - - switch (this.currentStep) - { - case 3: - { - stepInstruction = Application.getMessage(FacesContext.getCurrentInstance(), FINISH_INSTRUCTION_ID); - break; - } - default: - { - stepInstruction = Application.getMessage(FacesContext.getCurrentInstance(), DEFAULT_INSTRUCTION_ID); - } - } - - return stepInstruction; - } - - /** - * @see org.alfresco.web.bean.wizard.AbstractWizardBean#determineOutcomeForStep(int) - */ - protected String determineOutcomeForStep(int step) - { - String outcome = null; - - switch (step) - { - case 1: - { - outcome = "person-properties"; - break; - } - case 2: - { - outcome = "user-properties"; - break; - } - case 3: - { - outcome = "summary"; - break; - } - default: - { - outcome = CANCEL_OUTCOME; - } - } - - return outcome; - } - - /** - * @see org.alfresco.web.bean.wizard.AbstractWizardBean#finish() - */ - public String finish() - { - String outcome = FINISH_OUTCOME; - - // TODO: implement create new Person object from specified details - UserTransaction tx = null; - - try - { - FacesContext context = FacesContext.getCurrentInstance(); - tx = Repository.getUserTransaction(context); - tx.begin(); - - if (this.editMode) - { - // update the existing node in the repository - NodeRef nodeRef = getPerson().getNodeRef(); - - Map props = this.getNodeService().getProperties(nodeRef); - props.put(ContentModel.PROP_USERNAME, this.userName); - props.put(ContentModel.PROP_FIRSTNAME, this.firstName); - props.put(ContentModel.PROP_LASTNAME, this.lastName); - - // calculate whether we need to move the old home space or create new - NodeRef newHomeFolderRef; - NodeRef oldHomeFolderRef = (NodeRef)this.getNodeService().getProperty(nodeRef, ContentModel.PROP_HOMEFOLDER); - boolean moveHomeSpace = false; - boolean renameHomeSpace = false; - if (oldHomeFolderRef != null && this.getNodeService().exists(oldHomeFolderRef) == true) - { - // the original home folder ref exists so may need moving if it has been changed - ChildAssociationRef childAssocRef = this.getNodeService().getPrimaryParent(oldHomeFolderRef); - NodeRef currentHomeSpaceLocation = childAssocRef.getParentRef(); - if (this.homeSpaceName.length() != 0) - { - if (currentHomeSpaceLocation.equals(this.homeSpaceLocation) == false && - oldHomeFolderRef.equals(this.homeSpaceLocation) == false && - currentHomeSpaceLocation.equals(getCompanyHomeSpace()) == false && - currentHomeSpaceLocation.equals(getDefaultHomeSpace()) == false) - { - moveHomeSpace = true; - } - - String oldHomeSpaceName = Repository.getNameForNode(getNodeService(), oldHomeFolderRef); - if (oldHomeSpaceName.equals(this.homeSpaceName) == false && - oldHomeFolderRef.equals(this.homeSpaceLocation) == false && - oldHomeFolderRef.equals(this.defaultHomeSpaceRef) == false) - { - renameHomeSpace = true; - } - } - } - - if (logger.isDebugEnabled()) - logger.debug("Moving space: " + moveHomeSpace + " and renaming space: " + renameHomeSpace); - - if (moveHomeSpace == false && renameHomeSpace == false) - { - if (this.homeSpaceLocation != null && this.homeSpaceName.length() != 0) - { - newHomeFolderRef = createHomeSpace(this.homeSpaceLocation.getId(), this.homeSpaceName, false); - } - else if (this.homeSpaceLocation != null) - { - // location selected but no home space name entered, - // so the home ref should be set to the newly selected space - newHomeFolderRef = this.homeSpaceLocation; - - // set the permissions for this space so the user can access it - - } - else - { - // nothing selected - use Company Home by default - newHomeFolderRef = getCompanyHomeSpace(); - } - } - else - { - // either move, rename or both required - if (moveHomeSpace == true) - { - this.getNodeService().moveNode( - oldHomeFolderRef, - this.homeSpaceLocation, - ContentModel.ASSOC_CONTAINS, - this.getNodeService().getPrimaryParent(oldHomeFolderRef).getQName()); - } - newHomeFolderRef = oldHomeFolderRef; // ref ID doesn't change - - if (renameHomeSpace == true) - { - // change HomeSpace node name - this.getNodeService().setProperty(newHomeFolderRef, ContentModel.PROP_NAME, this.homeSpaceName); - } - } - - props.put(ContentModel.PROP_HOMEFOLDER, newHomeFolderRef); - props.put(ContentModel.PROP_EMAIL, this.email); - props.put(ContentModel.PROP_ORGID, this.companyId); - this.getNodeService().setProperties(nodeRef, props); - - // TODO: RESET HomeSpace Ref found in top-level navigation bar! - // NOTE: not need cos only admin can do this? - } - else - { - if (tenantService.isEnabled()) - { - String currentDomain = tenantService.getCurrentUserDomain(); - if (! currentDomain.equals(TenantService.DEFAULT_DOMAIN)) - { - if (! tenantService.isTenantUser(this.userName)) - { - // force domain onto the end of the username - this.userName = tenantService.getDomainUser(this.userName, currentDomain); - logger.warn("Added domain to username: " + this.userName); - } - else - { - try - { - tenantService.checkDomainUser(this.userName); - } - catch (RuntimeException re) - { - throw new AuthenticationException("User must belong to same domain as admin: " + currentDomain); - } - } - } - } - - if (this.password.equals(this.confirm)) - { - // create properties for Person type from submitted Form data - Map props = new HashMap(7, 1.0f); - props.put(ContentModel.PROP_USERNAME, this.userName); - props.put(ContentModel.PROP_FIRSTNAME, this.firstName); - props.put(ContentModel.PROP_LASTNAME, this.lastName); - NodeRef homeSpaceNodeRef; - if (this.homeSpaceLocation != null && this.homeSpaceName.length() != 0) - { - // create new - homeSpaceNodeRef = createHomeSpace(this.homeSpaceLocation.getId(), this.homeSpaceName, true); - } - else if (this.homeSpaceLocation != null) - { - // set to existing - homeSpaceNodeRef = homeSpaceLocation; - setupHomeSpacePermissions(homeSpaceNodeRef); - } - else - { - // default to Company Home - homeSpaceNodeRef = getCompanyHomeSpace(); - } - props.put(ContentModel.PROP_HOMEFOLDER, homeSpaceNodeRef); - props.put(ContentModel.PROP_EMAIL, this.email); - props.put(ContentModel.PROP_ORGID, this.companyId); - - // create the node to represent the Person - NodeRef newPerson = this.getPersonService().createPerson(props); - - // ensure the user can access their own Person object - this.getPermissionService().setPermission(newPerson, this.userName, getPermissionService().getAllPermission(), true); - - if (logger.isDebugEnabled()) logger.debug("Created Person node for username: " + this.userName); - - // create the ACEGI Authentication instance for the new user - this.getAuthenticationService().createAuthentication(this.userName, this.password.toCharArray()); - - if (logger.isDebugEnabled()) logger.debug("Created User Authentication instance for username: " + this.userName); - } - else - { - outcome = null; - Utils.addErrorMessage(Application.getMessage(context, UsersDialog.ERROR_PASSWORD_MATCH)); - } - } - - // commit the transaction - tx.commit(); - - // reset the richlist component so it rebinds to the users list - invalidateUserList(); - } - catch (Throwable e) - { - // rollback the transaction - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), ERROR), e - .getMessage()), e); - outcome = null; - } - - return outcome; - } - - /** - * @return Returns the summary data for the wizard. - */ - public String getSummary() - { - String homeSpaceLabel = this.homeSpaceName; - if (this.homeSpaceName.length() == 0 && this.homeSpaceLocation != null) - { - homeSpaceLabel = Repository.getNameForNode(this.getNodeService(), this.homeSpaceLocation); - } - - ResourceBundle bundle = Application.getBundle(FacesContext.getCurrentInstance()); - - return buildSummary(new String[] { bundle.getString("name"), bundle.getString("username"), - bundle.getString("password"), bundle.getString("homespace") }, new String[] { - this.firstName + " " + this.lastName, this.userName, "********", homeSpaceLabel }); - } - - /** - * Init the users screen - */ - public void setupUsers(ActionEvent event) - { - invalidateUserList(); - } - - /** - * Action listener called when the wizard is being launched for editing an - * existing node. - */ - public void startWizardForEdit(ActionEvent event) - { - UIActionLink link = (UIActionLink) event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - if (id != null && id.length() != 0) - { - try - { - // create the node ref, then our node representation - NodeRef ref = new NodeRef(Repository.getStoreRef(), id); - Node node = new Node(ref); - - // remember the Person node - setPerson(node); - - // set the wizard in edit mode - this.editMode = true; - - // populate the wizard's default values with the current value - // from the node being edited - init(); - populate(); - - // clear the UI state in preparation for finishing the action - // and returning to the main page - invalidateUserList(); - - if (logger.isDebugEnabled()) logger.debug("Started wizard : " + getWizardTitle() + " for editing"); - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), - Repository.ERROR_NODEREF), new Object[] { id })); - } - } - else - { - setPerson(null); - } - } - - /** - * @return Returns the companyId. - */ - public String getCompanyId() - { - return this.companyId; - } - - /** - * @param companyId - * The companyId to set. - */ - public void setCompanyId(String companyId) - { - this.companyId = companyId; - } - - /** - * @return Returns the email. - */ - public String getEmail() - { - return this.email; - } - - /** - * @param email - * The email to set. - */ - public void setEmail(String email) - { - this.email = email; - } - - /** - * @return Returns the firstName. - */ - public String getFirstName() - { - return this.firstName; - } - - /** - * @param firstName The firstName to set. - */ - public void setFirstName(String firstName) - { - this.firstName = firstName; - } - - /** - * @return Returns the homeSpaceLocation. - */ - public NodeRef getHomeSpaceLocation() - { - return this.homeSpaceLocation; - } - - /** - * @param homeSpaceLocation The homeSpaceLocation to set. - */ - public void setHomeSpaceLocation(NodeRef homeSpaceLocation) - { - this.homeSpaceLocation = homeSpaceLocation; - } - - /** - * @return Returns the homeSpaceName. - */ - public String getHomeSpaceName() - { - return this.homeSpaceName; - } - - /** - * @param homeSpaceName The homeSpaceName to set. - */ - public void setHomeSpaceName(String homeSpaceName) - { - this.homeSpaceName = homeSpaceName; - } - - /** - * @return Returns the lastName. - */ - public String getLastName() - { - return this.lastName; - } - - /** - * @param lastName The lastName to set. - */ - public void setLastName(String lastName) - { - this.lastName = lastName; - } - - /** - * @return Returns the userName. - */ - public String getUserName() - { - return this.userName; - } - - /** - * @param userName The userName to set. - */ - public void setUserName(String userName) - { - if (userName != null) - { - userName = userName.trim(); - } - - this.userName = userName; - } - - /** - * @return Returns the password. - */ - public String getPassword() - { - return this.password; - } - - /** - * @param password The password to set. - */ - public void setPassword(String password) - { - this.password = password; - } - - /** - * @return Returns the confirm password. - */ - public String getConfirm() - { - return this.confirm; - } - - /** - * @param confirm The confirm password to set. - */ - public void setConfirm(String confirm) - { - this.confirm = confirm; - } - - /** - * @return Returns the person context. - */ - public Node getPerson() - { - return this.person; - } - - /** - * @param person The person context to set. - */ - public void setPerson(Node person) - { - this.person = person; - } - - public boolean getEditMode() - { - return this.editMode; - } - - - // ------------------------------------------------------------------------------ - // Validator methods - - /** - * Validate password field data is acceptable - */ - public void validatePassword(FacesContext context, UIComponent component, Object value) throws ValidatorException - { - String pass = (String) value; - if (pass.length() < 5 || pass.length() > 12) - { - String err = "Password must be between 5 and 12 characters in length."; - throw new ValidatorException(new FacesMessage(err)); - } - - for (int i = 0; i < pass.length(); i++) - { - if (Character.isLetterOrDigit(pass.charAt(i)) == false) - { - String err = "Password can only contain characters or digits."; - throw new ValidatorException(new FacesMessage(err)); - } - } - } - - /** - * Validate Username field data is acceptable - */ - public void validateUsername(FacesContext context, UIComponent component, Object value) throws ValidatorException - { - String pass = (String) value; - if (pass.length() < 5 || pass.length() > 12) - { - String err = "Username must be between 5 and 12 characters in length."; - throw new ValidatorException(new FacesMessage(err)); - } - - for (int i = 0; i < pass.length(); i++) - { - if (Character.isLetterOrDigit(pass.charAt(i)) == false) - { - String err = "Username can only contain characters or digits."; - throw new ValidatorException(new FacesMessage(err)); - } - } - } - - /** - * Validate Email field data is acceptable - * - * @param context FacesContext - * @param component UIComponent - * @param value Object - * @throws ValidatorException - */ - public void validateEmail(FacesContext context, UIComponent component, Object value) throws ValidatorException - { - EmailValidator emailValidator = EmailValidator.getInstance(); - if (!emailValidator.isValid((String) value)) - { - String err =Application.getMessage(context, MSG_ERROR_MAIL_NOT_VALID); - throw new ValidatorException(new FacesMessage(err)); - } - } - - // ------------------------------------------------------------------------------ - // Helper methods - - /** - * Helper to return the company home space - * - * @return company home space NodeRef - */ - private NodeRef getCompanyHomeSpace() - { - if (this.companyHomeSpaceRef == null) - { - this.companyHomeSpaceRef = Repository.getCompanyRoot(FacesContext.getCurrentInstance()); - } - - return this.companyHomeSpaceRef; - } - - private NodeRef getDefaultHomeSpace() - { - if ((this.defaultHomeSpaceRef == null) || !getNodeService().exists(this.defaultHomeSpaceRef)) - { - String defaultHomeSpacePath = Application.getClientConfig(FacesContext.getCurrentInstance()).getDefaultHomeSpacePath(); - - NodeRef rootNodeRef = this.getNodeService().getRootNode(Repository.getStoreRef()); - List nodes = this.getSearchService().selectNodes(rootNodeRef, defaultHomeSpacePath, null, this.getNamespaceService(), - false); - - if (nodes.size() == 0) - { - return getCompanyHomeSpace(); - } - - this.defaultHomeSpaceRef = nodes.get(0); - } - - return this.defaultHomeSpaceRef; - } - - - - /** - * Create the specified home space if it does not exist, and return the ID - * - * @param locationId - * Parent location - * @param spaceName - * Home space to create, can be null to simply return the parent - * @param error - * True to throw an error if the space already exists, else - * ignore and return - * - * @return ID of the home space - */ - private NodeRef createHomeSpace(String locationId, String spaceName, boolean error) - { - NodeRef homeSpaceNodeRef = null; - if (spaceName != null && spaceName.length() != 0) - { - NodeRef parentRef = new NodeRef(Repository.getStoreRef(), locationId); - - // check for existance of home space with same name - return immediately - // if it exists or throw an exception an give user chance to enter another name - // TODO: this might be better replaced with an XPath query! - List children = this.getNodeService().getChildAssocs(parentRef); - for (ChildAssociationRef ref : children) - { - String childNodeName = (String) this.getNodeService().getProperty(ref.getChildRef(), ContentModel.PROP_NAME); - if (spaceName.equals(childNodeName)) - { - if (error) - { - throw new AlfrescoRuntimeException("A Home Space with the same name already exists."); - } - else - { - return ref.getChildRef(); - } - } - } - - // space does not exist already, create a new Space under it with - // the specified name - String qname = QName.createValidLocalName(spaceName); - ChildAssociationRef assocRef = this.getNodeService().createNode(parentRef, ContentModel.ASSOC_CONTAINS, - QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, qname), ContentModel.TYPE_FOLDER); - - NodeRef nodeRef = assocRef.getChildRef(); - - // set the name property on the node - this.getNodeService().setProperty(nodeRef, ContentModel.PROP_NAME, spaceName); - - if (logger.isDebugEnabled()) logger.debug("Created Home Space for with name: " + spaceName); - - // apply the uifacets aspect - icon, title and description props - Map uiFacetsProps = new HashMap(3); - uiFacetsProps.put(ApplicationModel.PROP_ICON, CreateSpaceWizard.DEFAULT_SPACE_ICON_NAME); - uiFacetsProps.put(ContentModel.PROP_TITLE, spaceName); - this.getNodeService().addAspect(nodeRef, ApplicationModel.ASPECT_UIFACETS, uiFacetsProps); - - setupHomeSpacePermissions(nodeRef); - - // return the ID of the created space - homeSpaceNodeRef = nodeRef; - } - - return homeSpaceNodeRef; - } - - /** - * Setup the default permissions for this and other users on the Home Space - * - * @param homeSpaceRef Home Space reference - */ - private void setupHomeSpacePermissions(NodeRef homeSpaceRef) - { - // Admin Authority has full permissions by default (automatic - set in the permission config) - // give full permissions to the new user - this.getPermissionService().setPermission(homeSpaceRef, this.userName, getPermissionService().getAllPermission(), true); - - // by default other users will only have GUEST access to the space contents - // or whatever is configured as the default in the web-client-xml config - String permission = getDefaultPermission(); - if (permission != null && permission.length() != 0) - { - this.getPermissionService().setPermission(homeSpaceRef, getPermissionService().getAllAuthorities(), permission, true); - } - - // the new user is the OWNER of their own space and always has full permissions - this.getOwnableService().setOwner(homeSpaceRef, this.userName); - this.getPermissionService().setPermission(homeSpaceRef, getPermissionService().getOwnerAuthority(), getPermissionService().getAllPermission(), true); - - // now detach (if we did this first we could not set any permissions!) - this.getPermissionService().setInheritParentPermissions(homeSpaceRef, false); - } - - /** - * @return default permission string to set for other users for a new Home Space - */ - private String getDefaultPermission() - { - ClientConfigElement config = Application.getClientConfig(FacesContext.getCurrentInstance()); - return config.getHomeSpacePermission(); - } - - private void invalidateUserList() - { - UIContextService.getInstance(FacesContext.getCurrentInstance()).notifyBeans(); - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/wizard/WizardManager.java b/war/src/main/java/org/alfresco/web/bean/wizard/WizardManager.java deleted file mode 100644 index c1cfa3c850..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/wizard/WizardManager.java +++ /dev/null @@ -1,670 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.wizard; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.el.ValueBinding; -import javax.faces.event.ActionEvent; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.config.WizardsConfigElement.ConditionalPageConfig; -import org.alfresco.web.config.WizardsConfigElement.PageConfig; -import org.alfresco.web.config.WizardsConfigElement.StepConfig; -import org.alfresco.web.config.WizardsConfigElement.WizardConfig; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.alfresco.web.ui.common.component.UIListItem; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean that manages the wizard framework - * - * @author gavinc - */ -public final class WizardManager implements Serializable -{ - private static final long serialVersionUID = -5029787339914973070L; - - /** public JSF bean name */ - public final static String BEAN_NAME = "WizardManager"; - - private static Log logger = LogFactory.getLog(WizardManager.class); - - private WizardState currentWizardState; - private Map paramsToApply; - - /** - * Sets the parameters the next wizard will initialise with - * - * @param params The parameters - */ - public void setupParameters(Map params) - { - this.paramsToApply = params; - } - - /** - * Action handler used to setup parameters for the wizard being launched - * - * @param event The event containing the parameters - */ - public void setupParameters(ActionEvent event) - { - // check the component the event come from was an action link - UIComponent component = event.getComponent(); - if (component instanceof UIActionLink) - { - // store the parameters - this.paramsToApply = ((UIActionLink)component).getParameterMap(); - - // make sure "null" parameters are actually null, this can occur - // when null parameters are sent to the client and posted back - for (String name : this.paramsToApply.keySet()) - { - String value = this.paramsToApply.get(name); - if (value != null && value.equalsIgnoreCase("null")) - { - this.paramsToApply.put(name, null); - } - } - } - } - - /** - * Sets the current wizard - * - * @param config The configuration for the wizard to set - */ - public void setCurrentWizard(WizardConfig config) - { - // make sure the managed bean is present - String beanName = config.getManagedBean(); - - Object bean = FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), beanName); - - if (bean == null) - { - throw new AlfrescoRuntimeException("Failed to start wizard as managed bean '" + beanName + - "' has not been defined"); - } - - // make sure the bean implements the IWizardBean interface - IWizardBean wizard = null; - if (bean instanceof IWizardBean) - { - wizard = (IWizardBean)bean; - } - else - { - throw new AlfrescoRuntimeException("Failed to start wizard as managed bean '" + beanName + - "' does not implement the required IWizardBean interface"); - } - - // create the WizardState object - this.currentWizardState = new WizardState(config, wizard); - - // initialise the managed bean - wizard.init(this.paramsToApply); - - // reset the current parameters so subsequent wizards don't get them - this.paramsToApply = null; - - // setup the first step - determineCurrentPage(); - } - - /** - * Returns the state of the currently active wizard - * - * @return Current wizard's state - */ - public WizardState getState() - { - return this.currentWizardState; - } - - /** - * Restores the wizard represented by the given WizardState object. - * NOTE: The wizard's restored() method is also called during this - * method. - * - * @param state The WizardState for the wizard to restore - */ - public void restoreState(WizardState state) - { - this.currentWizardState = state; - - // retrieve the wizard and call it's restored() method - this.currentWizardState.getWizard().restored(); - } - - /** - * Returns the config for the current wizard - * - * @return The current wizard config - */ - public WizardConfig getCurrentWizard() - { - return this.currentWizardState.getConfig(); - } - - /** - * Returns the current wizard bean being managed - * - * @return The current managed bean - */ - public IWizardBean getBean() - { - return this.currentWizardState.getWizard(); - } - - /** - * Returns the icon to use for the current wizard - * - * @return The icon - */ - public String getIcon() - { - return this.currentWizardState.getConfig().getIcon(); - } - - /** - * Returns the error message to use in error conditions - * - * @return The error message - */ - public String getErrorMessage() - { - return Application.getMessage(FacesContext.getCurrentInstance(), - this.currentWizardState.getConfig().getErrorMessageId()); - } - - /** - * Returns the resolved title to use for the wizard - * - * @return The title - */ - public String getTitle() - { - // try and get the title directly from the wizard - String title = this.currentWizardState.getWizard().getContainerTitle(); - - if (title == null) - { - // try and get the title via a message bundle key - title = this.currentWizardState.getConfig().getTitleId(); - - if (title != null) - { - title = Application.getMessage(FacesContext.getCurrentInstance(), title); - } - else - { - // try and get the title from the configuration - title = this.currentWizardState.getConfig().getTitle(); - } - } - - return title; - } - - /** - * Returns the resolved subtitle to use for the wizard - * - * @return The subtitle - */ - public String getSubTitle() - { - // try and get the title directly from the wizard - String subTitle = this.currentWizardState.getWizard().getContainerSubTitle(); - - if (subTitle == null) - { - // try and get the title via a message bundle key - subTitle = this.currentWizardState.getConfig().getSubTitleId(); - - if (subTitle != null) - { - subTitle = Application.getMessage(FacesContext.getCurrentInstance(), subTitle); - } - else - { - // try and get the title from the configuration - subTitle = this.currentWizardState.getConfig().getSubTitle(); - } - } - - return subTitle; - } - - /** - * Returns the resolved description to use for the wizard - * - * @return The description - */ - public String getDescription() - { - // try and get the description directly from the dialog - String desc = this.currentWizardState.getWizard().getContainerDescription(); - if (desc == null) - { - // try and get the description via a message bundle key - desc = this.currentWizardState.getConfig().getDescriptionId(); - - if (desc != null) - { - desc = Application.getMessage(FacesContext.getCurrentInstance(), desc); - } - else - { - // try and get the description from the configuration - desc = this.currentWizardState.getConfig().getDescription(); - } - } - - return desc; - } - - /** - * Returns the current step position - * - * @return Current step position - */ - public int getCurrentStep() - { - return this.currentWizardState.getCurrentStep(); - } - - /** - * Returns the current step position as a string for use in the UI - * - * @return Current step position as a string - */ - public String getCurrentStepAsString() - { - return Integer.toString(this.currentWizardState.getCurrentStep()); - } - - /** - * Returns the name of the current step, wizards should use - * the name of the step rather than the step number to discover - * the position as extra steps can be added via configuration. - * - * @return The name of the current step - */ - public String getCurrentStepName() - { - return ((StepConfig)this.currentWizardState.getSteps().get( - this.currentWizardState.getCurrentStep()-1)).getName(); - } - - /** - * Returns a list of UIListItems representing the steps of the wizard - * - * @return List of steps to display in UI - */ - public List getStepItems() - { - List items = new ArrayList(this.currentWizardState.getSteps().size()); - - for (int x = 0; x < this.currentWizardState.getSteps().size(); x++) - { - String uiStepNumber = Integer.toString(x + 1); - StepConfig stepCfg = this.currentWizardState.getSteps().get(x); - UIListItem item = new UIListItem(); - item.setValue(uiStepNumber); - - // get the title for the step - String stepTitle = stepCfg.getTitleId(); - if (stepTitle != null) - { - stepTitle = Application.getMessage(FacesContext.getCurrentInstance(), stepTitle); - } - else - { - stepTitle = stepCfg.getTitle(); - } - - // get the tooltip for the step - String stepTooltip = stepCfg.getDescriptionId(); - if (stepTooltip != null) - { - stepTooltip = Application.getMessage(FacesContext.getCurrentInstance(), stepTooltip); - } - else - { - stepTooltip = stepCfg.getDescription(); - } - - // set the label and tooltip - item.setLabel(uiStepNumber + ". " + stepTitle); - item.setTooltip(stepTooltip); - - items.add(item); - } - - return items; - } - - /** - * Returns the current page of the wizard (depends on the current step position) - * - * @return The page - */ - public String getPage() - { - return this.currentWizardState.getCurrentPageCfg().getPath(); - } - - /** - * Returns the title of the current step - * - * @return The step title - */ - public String getStepTitle() - { - String result = this.currentWizardState.getWizard().getStepTitle(); - if (result == null) - { - result = this.currentWizardState.getCurrentPageCfg().getTitleId(); - result = (result != null - ? Application.getMessage(FacesContext.getCurrentInstance(), result) - : this.currentWizardState.getCurrentPageCfg().getTitle()); - } - return result; - } - - /** - * Returns the description of the current step - * - * @return The step description - */ - public String getStepDescription() - { - String result = this.currentWizardState.getWizard().getStepDescription(); - if (result == null) - { - result = this.currentWizardState.getCurrentPageCfg().getDescriptionId(); - result = (result != null - ? Application.getMessage(FacesContext.getCurrentInstance(), result) - : this.currentWizardState.getCurrentPageCfg().getDescription()); - } - return result; - } - - /** - * Returns the instructions for the current step - * - * @return The step instructions - */ - public String getStepInstructions() - { - String instruction = this.currentWizardState.getCurrentPageCfg().getInstructionId(); - - if (instruction != null) - { - instruction = Application.getMessage(FacesContext.getCurrentInstance(), instruction); - } - else - { - instruction = this.currentWizardState.getCurrentPageCfg().getInstruction(); - } - - return instruction; - } - - /** - * Returns the label to use for the next button - * - * @return The next button label - */ - public String getNextButtonLabel() - { - return this.currentWizardState.getWizard().getNextButtonLabel(); - } - - /** - * Determines whether the next button on the wizard should be disabled - * - * @return true if the button should be disabled - */ - public boolean getNextButtonDisabled() - { - IWizardBean wb = this.currentWizardState.getWizard(); - - if (wb.isFinished()) - { - return true; - } - - return (this.currentWizardState.getCurrentStep() == this.currentWizardState.getSteps().size() || - wb.getNextButtonDisabled()); - } - - /** - * Returns the label to use for the back button - * - * @return The back button label - */ - public String getBackButtonLabel() - { - return this.currentWizardState.getWizard().getBackButtonLabel(); - } - - /** - * Determines whether the back button on the wizard should be disabled - * - * @return true if the button should be disabled - */ - public boolean getBackButtonDisabled() - { - if (this.currentWizardState.getWizard().isFinished()) - { - return true; - } - - return this.currentWizardState.getCurrentStep() == 1; - } - - /** - * Returns the label to use for the cancel button - * - * @return The cancel button label - */ - public String getCancelButtonLabel() - { - return this.currentWizardState.getWizard().getCancelButtonLabel(); - } - - /** - * Returns the label to use for the finish button - * - * @return The finish button label - */ - public String getFinishButtonLabel() - { - return this.currentWizardState.getWizard().getFinishButtonLabel(); - } - - /** - * Determines whether the finish button on the wizard should be disabled - * - * @return true if the button should be disabled - */ - public boolean getFinishButtonDisabled() - { - IWizardBean wb = this.currentWizardState.getWizard(); - - if (wb.isFinished()) - { - return true; - } - - return (this.currentWizardState.getCurrentStep() != this.currentWizardState.getSteps().size() && - wb.getFinishButtonDisabled()); - } - - /** - * Method handler called when the next button of the wizard is pressed - */ - public void next() - { - // calculate next step number and update wizard state - int currentStep = this.currentWizardState.getCurrentStep(); - int noSteps = this.currentWizardState.getSteps().size(); - currentStep++; - - // check we haven't gone past the end (this can happen if the next - // button is pressed too many times) - if (currentStep > noSteps) - { - currentStep = noSteps; - } - - this.currentWizardState.setCurrentStep(currentStep); - - if (logger.isDebugEnabled()) - logger.debug("next called, current step is now: " + this.currentWizardState.getCurrentStep()); - - // tell the wizard the next button has been pressed - this.currentWizardState.getWizard().next(); - - determineCurrentPage(); - } - - /** - * Method handler called when the back button of the wizard is pressed - */ - public void back() - { - // calculate next step number and update wizard state - int currentStep = this.currentWizardState.getCurrentStep(); - currentStep--; - - // check we haven't gone past the beginning (this can - // happen if the back button is pressed too many times) - if (currentStep < 1) - { - currentStep = 1; - } - - this.currentWizardState.setCurrentStep(currentStep); - - if (logger.isDebugEnabled()) - logger.debug("back called, current step is now: " + this.currentWizardState.getCurrentStep()); - - // tell the wizard the back button has been pressed - this.currentWizardState.getWizard().back(); - - determineCurrentPage(); - } - - /** - * Method handler called when the finish button of the wizard is pressed - * - * @return The outcome - */ - public String finish() - { - return this.currentWizardState.getWizard().finish(); - } - - /** - * Method handler called when the cancel button of the wizard is pressed - * - * @return The outcome - */ - public String cancel() - { - return this.currentWizardState.getWizard().cancel(); - } - - /** - * Sets up the current page to show in the wizard - */ - protected void determineCurrentPage() - { - // reset the current page config in the state object - this.currentWizardState.setCurrentPageCfg(null); - - PageConfig currentPageCfg = null; - - // get the config for the current step position - StepConfig stepCfg = this.currentWizardState.getSteps().get( - this.currentWizardState.getCurrentStep()-1); - - // is the step conditional? - if (stepCfg.hasConditionalPages()) - { - FacesContext context = FacesContext.getCurrentInstance(); - - // test each conditional page in turn - List pages = stepCfg.getConditionalPages(); - - for (ConditionalPageConfig pageCfg : pages) - { - String condition = pageCfg.getCondition(); - - if (logger.isDebugEnabled()) - logger.debug("Evaluating condition: " + condition); - - ValueBinding vb = context.getApplication().createValueBinding(condition); - Object obj = vb.getValue(context); - if (obj instanceof Boolean && ((Boolean)obj).booleanValue()) - { - currentPageCfg = pageCfg; - break; - } - } - } - - // if none of the conditions passed use the default page - if (currentPageCfg == null) - { - currentPageCfg = stepCfg.getDefaultPage(); - } - - if (currentPageCfg == null) - { - throw new AlfrescoRuntimeException("Failed to determine page for step '" + stepCfg.getName() + - "'. Make sure a default page is configured."); - } - - // save the current page config in the state object - this.currentWizardState.setCurrentPageCfg(currentPageCfg); - - if (logger.isDebugEnabled()) - logger.debug("Config for current page: " + this.currentWizardState.getCurrentPageCfg()); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/wizard/WizardState.java b/war/src/main/java/org/alfresco/web/bean/wizard/WizardState.java deleted file mode 100644 index 9fde7e22b9..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/wizard/WizardState.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.wizard; - -import java.io.Serializable; -import java.util.List; - -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.config.WizardsConfigElement.PageConfig; -import org.alfresco.web.config.WizardsConfigElement.StepConfig; -import org.alfresco.web.config.WizardsConfigElement.WizardConfig; - -/** - * Object responsible for holding the current state of an active wizard. - * - * @author gavinc - */ -public final class WizardState implements Serializable -{ - private static final long serialVersionUID = -6816474382767569256L; - - private int currentStep = 1; - private PageConfig currentPageCfg; - private WizardConfig config; - private IWizardBean wizard; - private List steps; - - /** - * Default constructor - * - * @param config The configuration for the wizard - * @param wizard The wizard bean instance - */ - public WizardState(WizardConfig config, IWizardBean wizard) - { - this.config = config; - this.wizard = wizard; - - this.steps = this.config.getStepsAsList(); - } - - /** - * Sets the configuration for the current page of the wizard - * - * @param currentPageCfg The configuration - */ - public void setCurrentPageCfg(PageConfig currentPageCfg) - { - this.currentPageCfg = currentPageCfg; - } - - /** - * Sets the current step the wizard is on - * - * @param currentStep The current step number - */ - public void setCurrentStep(int currentStep) - { - this.currentStep = currentStep; - } - - /** - * Returns the wizard bean instance - * - * @return The wizard bean instance - */ - public IWizardBean getWizard() - { - return this.wizard; - } - - /** - * Returns the configuration for the current wizard - * - * @return The wizard configuration - */ - public WizardConfig getConfig() - { - return this.config; - } - - /** - * Returns the configuration for the current page of the wizard - * - * @return The current page configuration - */ - public PageConfig getCurrentPageCfg() - { - return currentPageCfg; - } - - /** - * The current step the wizard is on - * - * @return The current wizard step - */ - public int getCurrentStep() - { - return currentStep; - } - - /** - * Returns the list of steps the wizard has - * - * @return List of wizard steps - */ - public List getSteps() - { - return steps; - } - - @Override - public String toString() - { - return AlfrescoNavigationHandler.WIZARD_PREFIX + this.config.getName() + - "[" + this.currentStep + "]"; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/workflow/BaseReassignDialog.java b/war/src/main/java/org/alfresco/web/bean/workflow/BaseReassignDialog.java deleted file mode 100644 index b5783179c4..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/workflow/BaseReassignDialog.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.workflow; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.ResourceBundle; - -import javax.faces.context.FacesContext; -import javax.faces.model.SelectItem; -import javax.transaction.UserTransaction; - -import org.alfresco.query.PagingRequest; -import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.service.cmr.search.ResultSet; -import org.alfresco.service.cmr.security.PersonService; -import org.alfresco.service.cmr.security.PersonService.PersonInfo; -import org.alfresco.service.cmr.workflow.WorkflowService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.ui.common.SortableSelectItem; -import org.alfresco.web.ui.common.Utils; - -/** - * Base dialog bean for workflow user reassignment. - * - * @author gavinc - * @author Kevin Roast - */ -public abstract class BaseReassignDialog extends BaseDialogBean -{ - /** - * - */ - private static final long serialVersionUID = 3392941403282035753L; - - private static final String MSG_SEARCH_MINIMUM = "picker_search_min"; - - transient private WorkflowService workflowService; - transient private PersonService personService; - - - // ------------------------------------------------------------------------------ - // Bean Getters and Setters - - /** - * Sets the workflow service to use - * - * @param workflowService The WorkflowService instance - */ - public void setWorkflowService(WorkflowService workflowService) - { - this.workflowService = workflowService; - } - - protected WorkflowService getWorkflowService() - { - if (workflowService == null) - { - workflowService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getWorkflowService(); - } - return workflowService; - } - - /** - * @param personService The PersonService to set. - */ - public void setPersonService(PersonService personService) - { - this.personService = personService; - } - - protected PersonService getPersonService() - { - if (personService == null) - { - personService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getPersonService(); - } - return personService; - } - - /** - * Property accessed by the Generic Picker component. - * - * @return the array of filter options to show in the users/groups picker - */ - public SelectItem[] getFilters() - { - ResourceBundle bundle = Application.getBundle(FacesContext.getCurrentInstance()); - return new SelectItem[] {new SelectItem("0", bundle.getString("users"))}; - } - - /** - * Query callback method executed by the Generic Picker component. - * This method is part of the contract to the Generic Picker, it is up to the backing bean - * to execute whatever query is appropriate and return the results. - * - * @param filterIndex Index of the filter drop-down selection - * @param contains Text from the contains textbox - * - * @return An array of SelectItem objects containing the results to display in the picker. - */ - public SelectItem[] pickerCallback(int filterIndex, String contains) - { - FacesContext context = FacesContext.getCurrentInstance(); - - // quick exit if not enough characters entered for a search - String search = contains.trim(); - int searchMin = Application.getClientConfig(context).getPickerSearchMinimum(); - if (search.length() < searchMin) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, MSG_SEARCH_MINIMUM), searchMin)); - return new SelectItem[0]; - } - - SelectItem[] items; - - UserTransaction tx = null; - ResultSet resultSet = null; - try - { - tx = Repository.getUserTransaction(context, true); - tx.begin(); - - int maxResults = Application.getClientConfig(context).getInviteUsersMaxResults(); - if(maxResults <= 0) - { - maxResults = Utils.getPersonMaxResults(); - } - - List persons = getPersonService().getPeople( - Utils.generatePersonFilter(contains.trim()), - true, - Utils.generatePersonSort(), - new PagingRequest(maxResults, null) - ).getPage(); - - ArrayList itemList = new ArrayList(persons.size()); - for (PersonInfo person : persons) - { - String username = person.getUserName(); - if (AuthenticationUtil.getGuestUserName().equals(username) == false) - { - String firstName = person.getFirstName(); - String lastName = person.getLastName(); - String name = (firstName != null ? firstName : "") + ' ' + (lastName != null ? lastName : ""); - SelectItem item = new SortableSelectItem(username, name + " [" + username + "]", lastName != null ? lastName : username); - itemList.add(item); - } - } - items = new SelectItem[itemList.size()]; - itemList.toArray(items); - - Arrays.sort(items); - - // commit the transaction - tx.commit(); - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - - items = new SelectItem[0]; - } - finally - { - if (resultSet != null) - { - resultSet.close(); - } - } - - return items; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/workflow/CancelWorkflowDialog.java b/war/src/main/java/org/alfresco/web/bean/workflow/CancelWorkflowDialog.java deleted file mode 100644 index 55c2e5f33a..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/workflow/CancelWorkflowDialog.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.workflow; - -import java.text.MessageFormat; -import java.util.Map; - -import javax.faces.context.FacesContext; - -import org.alfresco.service.cmr.workflow.WorkflowInstance; -import org.alfresco.service.cmr.workflow.WorkflowService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.Repository; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean implementation for the "Cancel Workflow" dialog - * - * @author gavinc - */ -public class CancelWorkflowDialog extends BaseDialogBean -{ - private static final long serialVersionUID = -7875582893750792200L; - - transient private WorkflowInstance workflowInstance; - transient private WorkflowService workflowService; - - private static final Log logger = LogFactory.getLog(CancelWorkflowDialog.class); - - // ------------------------------------------------------------------------------ - // Dialog implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - // make sure the workflow instance id has been passed - String workflowInstanceId = this.parameters.get("workflow-instance-id"); - if (workflowInstanceId == null || workflowInstanceId.length() == 0) - { - throw new IllegalArgumentException("Cancel workflow dialog called without workflow instance id"); - } - - this.workflowInstance = getWorkflowService().getWorkflowById(workflowInstanceId); - if (this.workflowInstance == null) - { - throw new IllegalArgumentException("Failed to find workflow instance for id: " + workflowInstanceId); - } - } - - @Override - protected String finishImpl(FacesContext context, String outcome) - throws Exception - { - if (logger.isDebugEnabled()) - logger.debug("Cancelling workflow with id: " + this.getWorkflowInstance().getId()); - - WorkflowInstance instance = this.getWorkflowInstance(); - if(instance.isActive()) { - // cancel the workflow - this.getWorkflowService().cancelWorkflow(this.getWorkflowInstance().getId()); - } - else - { - // delete the workflow - this.getWorkflowService().deleteWorkflow(this.getWorkflowInstance().getId()); - } - - if (logger.isDebugEnabled()) - logger.debug("Cancelled workflow with id: " + this.getWorkflowInstance().getId()); - - return outcome; - } - - @Override - protected String getErrorMessageId() - { - return "error_cancel_workflow"; - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "no"); - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "yes"); - } - - // ------------------------------------------------------------------------------ - // Bean Getters and Setters - - /** - * Returns the confirmation to display to the user before deleting the content. - * - * @return The formatted message to display - */ - public String getConfirmMessage() - { - String confirmMsg = Application.getMessage(FacesContext.getCurrentInstance(), - "cancel_workflow_confirm"); - - String workflowLabel = this.getWorkflowInstance().getDefinition().getTitle(); - if (this.getWorkflowInstance().getDescription() != null && this.getWorkflowInstance().getDescription().length() > 0) - { - workflowLabel = workflowLabel + " (" + this.getWorkflowInstance().getDescription() + ")"; - } - - return MessageFormat.format(confirmMsg, new Object[] {workflowLabel}); - } - - /** - * Returns the workflow service instance - * - * @return WorkflowService instance - */ - public WorkflowService getWorkflowService() - { - if (workflowService == null) - { - workflowService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getWorkflowService(); - } - return workflowService; - } - - /** - * Sets the workflow service to use - * - * @param workflowService The WorkflowService instance - */ - public void setWorkflowService(WorkflowService workflowService) - { - this.workflowService = workflowService; - } - - protected WorkflowInstance getWorkflowInstance() - { - if (workflowInstance == null) - { - String workflowInstanceId = this.parameters.get("workflow-instance-id"); - if (workflowInstanceId == null || workflowInstanceId.length() == 0) - { - throw new IllegalArgumentException("Cancel workflow dialog called without workflow instance id"); - } - - this.workflowInstance = getWorkflowService().getWorkflowById(workflowInstanceId); - if (this.workflowInstance == null) - { - throw new IllegalArgumentException("Failed to find workflow instance for id: " + workflowInstanceId); - } - } - return workflowInstance; - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/workflow/ManageTaskDialog.java b/war/src/main/java/org/alfresco/web/bean/workflow/ManageTaskDialog.java deleted file mode 100644 index 892492a613..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/workflow/ManageTaskDialog.java +++ /dev/null @@ -1,921 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ - -package org.alfresco.web.bean.workflow; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.workflow.WorkflowModel; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.workflow.WorkflowInstance; -import org.alfresco.service.cmr.workflow.WorkflowService; -import org.alfresco.service.cmr.workflow.WorkflowTask; -import org.alfresco.service.cmr.workflow.WorkflowTaskDefinition; -import org.alfresco.service.cmr.workflow.WorkflowTaskState; -import org.alfresco.service.cmr.workflow.WorkflowTransition; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.AlfrescoNavigationHandler; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.dialog.BaseDialogBean; -import org.alfresco.web.bean.repository.MapNode; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.NodePropertyResolver; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.repository.TransientNode; -import org.alfresco.web.bean.repository.User; -import org.alfresco.web.config.DialogsConfigElement.DialogButtonConfig; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.alfresco.web.ui.common.component.data.UIRichList; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean implementation for the "Manage Task" dialog. - * - * @author gavinc - */ -public class ManageTaskDialog extends BaseDialogBean -{ - private static final long serialVersionUID = -3209544870892993135L; - - transient private WorkflowService workflowService; - protected Node taskNode; - transient private WorkflowTask task; - transient private WorkflowInstance workflowInstance; - transient private WorkflowTransition[] transitions; - protected NodeRef workflowPackage; - protected List resources; - protected TaskCompleteResolver completeResolver = new TaskCompleteResolver(); - protected UIRichList packageItemsRichList; - protected List packageItemsToAdd; - protected List packageItemsToRemove; - protected String[] itemsToAdd; - protected boolean isItemBeingAdded = false; - - private final static Log LOGGER = LogFactory.getLog(ManageTaskDialog.class); - - protected static final String ID_PREFIX = "transition_"; - protected static final String CLIENT_ID_PREFIX = AlfrescoNavigationHandler.DIALOG_PREFIX + ID_PREFIX; - - // ------------------------------------------------------------------------------ - // Dialog implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - // reset variables - this.task = null; - this.taskNode = null; - this.workflowInstance = null; - this.transitions = null; - this.workflowPackage = null; - this.resources = null; - this.itemsToAdd = null; - this.packageItemsToAdd = null; - this.packageItemsToRemove = null; - this.isItemBeingAdded = false; - if (this.packageItemsRichList != null) - { - this.packageItemsRichList.setValue(null); - this.packageItemsRichList = null; - } - - // get the task details - String taskId = this.parameters.get("id"); - this.task = this.getWorkflowService().getTaskById(taskId); - - if (this.task != null) - { - // setup a transient node to represent the task we're managing - WorkflowTaskDefinition taskDef = this.task.definition; - this.taskNode = new TransientNode(taskDef.metadata.getName(), "task_" + System.currentTimeMillis(), - this.task.properties); - - // get access to the workflow instance for the task - this.workflowInstance = this.task.path.instance; - - // setup the workflow package for the task - this.workflowPackage = (NodeRef) this.task.properties.get(WorkflowModel.ASSOC_PACKAGE); - - if (LOGGER.isDebugEnabled()) - { - LOGGER.debug("Task: " + this.task); - LOGGER.debug("Trasient node: " + this.taskNode); - Boolean isSystemPackage = (Boolean) this.getNodeService().getProperty(this.workflowPackage, - WorkflowModel.PROP_IS_SYSTEM_PACKAGE); - LOGGER.debug("Workflow package: " + this.workflowPackage + " system package: " + isSystemPackage); - } - } - } - - @Override - public void restored() - { - // reset the workflow package rich list so everything gets re-evaluated - if (this.packageItemsRichList != null) - { - this.packageItemsRichList.setValue(null); - this.packageItemsRichList = null; - } - } - - @Override - protected String finishImpl(FacesContext context, String outcome) throws Exception - { - if (LOGGER.isDebugEnabled()) - LOGGER.debug("Saving task: " + this.getWorkflowTask().id); - - // before updating the task still exists and is not completed - WorkflowTask checkTask = this.getWorkflowService().getTaskById(this.getWorkflowTask().id); - if (checkTask == null || checkTask.state == WorkflowTaskState.COMPLETED) - { - Utils.addErrorMessage(Application.getMessage(context, "invalid_task")); - return outcome; - } - - // prepare the edited parameters for saving - Map params = WorkflowUtil.prepareTaskParams(this.taskNode); - - if (LOGGER.isDebugEnabled()) - LOGGER.debug("Saving task with parameters: " + params); - - // update the task with the updated parameters and resources - updateResources(); - this.getWorkflowService().updateTask(this.getWorkflowTask().id, params, null, null); - - return outcome; - } - - @Override - public List getAdditionalButtons() - { - List buttons = null; - - if (this.getWorkflowTask() != null) - { - // get the transitions available from this task and - // show them in the dialog as additional buttons - this.transitions = this.getWorkflowTask().path.node.transitions; - boolean isPooledTask = isPooledTask(); - - if (isPooledTask || this.transitions != null) - { - buttons = new ArrayList(this.transitions.length + 1); - - if (isPooledTask) - { - if (this.taskNode.getProperties().get(ContentModel.PROP_OWNER) == null) - { - buttons.add(new DialogButtonConfig("button_take_ownership", null, "take_ownership", - "#{DialogManager.bean.takeOwnership}", "false", null)); - } - else - { - buttons.add(new DialogButtonConfig("button_return_to_pool", null, "return_ownership", - "#{DialogManager.bean.returnOwnership}", "false", null)); - } - } - - if (this.transitions != null) - { - Object hiddenTransitions = this.taskNode.getProperties().get(WorkflowModel.PROP_HIDDEN_TRANSITIONS); - for (WorkflowTransition trans : this.transitions) - { - if (hiddenTransitions == null - || (hiddenTransitions instanceof String && ((String) hiddenTransitions).equals("")) - || (hiddenTransitions instanceof String && !((String) hiddenTransitions) - .equals(trans.id)) || (hiddenTransitions instanceof List) - && !((List) hiddenTransitions).contains(trans.id)) - { - if (this.taskNode.getProperties().get(ContentModel.PROP_OWNER) != null) - { - buttons.add(new DialogButtonConfig(ID_PREFIX + trans.title, trans.title, null, - "#{DialogManager.bean.transition}", "false", null)); - } - } - } - } - } - } - - return buttons; - } - - @Override - public String getFinishButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "save_changes"); - } - - @Override - public boolean getFinishButtonDisabled() - { - return false; - } - - @Override - public String getContainerTitle() - { - String titleStart = Application.getMessage(FacesContext.getCurrentInstance(), "manage_task_title"); - - return titleStart + ": " + this.getWorkflowTask().title; - } - - @Override - public String getContainerDescription() - { - return this.getWorkflowTask().description; - } - - // ------------------------------------------------------------------------------ - // Event handlers - - @SuppressWarnings("deprecation") - public String takeOwnership() - { - String outcome = getDefaultFinishOutcome(); - - if (LOGGER.isDebugEnabled()) - LOGGER.debug("Taking ownership of task: " + this.getWorkflowTask().id); - - FacesContext context = FacesContext.getCurrentInstance(); - - // before taking ownership check the task still exists and is not - // completed - WorkflowTask checkTask = this.getWorkflowService().getTaskById(this.getWorkflowTask().id); - if (checkTask == null || checkTask.state == WorkflowTaskState.COMPLETED) - { - Utils.addErrorMessage(Application.getMessage(context, "invalid_task")); - return outcome; - } - - UserTransaction tx = null; - - try - { - tx = Repository.getUserTransaction(context); - tx.begin(); - - // prepare the edited parameters for saving - User user = Application.getCurrentUser(context); - String userName = user.getUserName(); - Map params = new HashMap(); - params.put(ContentModel.PROP_OWNER, userName); - - // update the task with the updated parameters and resources - updateResources(); - this.getWorkflowService().updateTask(this.getWorkflowTask().id, params, null, null); - - // commit the changes - tx.commit(); - } - catch (Throwable e) - { - // rollback the transaction - try - { - if (tx != null) - { - tx.rollback(); - } - } - catch (Exception ex) - { - } - Utils.addErrorMessage(formatErrorMessage(e), e); - outcome = this.getErrorOutcome(e); - } - - return outcome; - } - - @SuppressWarnings("deprecation") - public String returnOwnership() - { - String outcome = getDefaultFinishOutcome(); - - if (LOGGER.isDebugEnabled()) - LOGGER.debug("Returning ownership of task to pool: " + this.getWorkflowTask().id); - - FacesContext context = FacesContext.getCurrentInstance(); - // before returning ownership check the task still exists and is not - // completed - WorkflowTask checkTask = this.getWorkflowService().getTaskById(this.getWorkflowTask().id); - if (checkTask == null || checkTask.state == WorkflowTaskState.COMPLETED) - { - Utils.addErrorMessage(Application.getMessage(context, "invalid_task")); - return outcome; - } - - UserTransaction tx = null; - - try - { - tx = Repository.getUserTransaction(context); - tx.begin(); - - // prepare the edited parameters for saving - Map params = new HashMap(); - params.put(ContentModel.PROP_OWNER, null); - - // update the task with the updated parameters and resources - updateResources(); - this.getWorkflowService().updateTask(this.getWorkflowTask().id, params, null, null); - - // commit the changes - tx.commit(); - } - catch (Throwable e) - { - // rollback the transaction - try - { - if (tx != null) - { - tx.rollback(); - } - } - catch (Exception ex) - { - } - Utils.addErrorMessage(formatErrorMessage(e), e); - outcome = this.getErrorOutcome(e); - } - - return outcome; - } - - @SuppressWarnings("deprecation") - public String transition() - { - String outcome = getDefaultFinishOutcome(); - - if (LOGGER.isDebugEnabled()) - LOGGER.debug("Transitioning task: " + this.getWorkflowTask().id); - - // before transitioning check the task still exists and is not completed - FacesContext context = FacesContext.getCurrentInstance(); - WorkflowTask checkTask = this.getWorkflowService().getTaskById(this.getWorkflowTask().id); - if (checkTask == null || checkTask.state == WorkflowTaskState.COMPLETED) - { - Utils.addErrorMessage(Application.getMessage(context, "invalid_task")); - return outcome; - } - - // to find out which transition button was pressed we need - // to look for the button's id in the request parameters, - // the first non-null result is the button that was pressed. - Map reqParams = context.getExternalContext().getRequestParameterMap(); - - String selectedTransition = null; - for (WorkflowTransition trans : this.getWorkflowTransitions()) - { - Object result = reqParams.get(CLIENT_ID_PREFIX + FacesHelper.makeLegalId(trans.title)); - if (result != null) - { - // this was the button that was pressed - selectedTransition = trans.id; - break; - } - } - - UserTransaction tx = null; - - try - { - tx = Repository.getUserTransaction(context); - tx.begin(); - - // prepare the edited parameters for saving - Map params = WorkflowUtil.prepareTaskParams(this.taskNode); - - if (LOGGER.isDebugEnabled()) - LOGGER.debug("Transitioning task with parameters: " + params); - - // update the task with the updated parameters and resources - updateResources(); - this.getWorkflowService().updateTask(this.getWorkflowTask().id, params, null, null); - - // signal the selected transition to the workflow task - this.getWorkflowService().endTask(this.getWorkflowTask().id, selectedTransition); - - // commit the changes - tx.commit(); - - if (LOGGER.isDebugEnabled()) - LOGGER.debug("Ended task with transition: " + selectedTransition); - } - catch (Throwable e) - { - // rollback the transaction - try - { - if (tx != null) - { - tx.rollback(); - } - } - catch (Exception ex) - { - } - Utils.addErrorMessage(formatErrorMessage(e), e); - outcome = this.getErrorOutcome(e); - } - - return outcome; - } - - /** - * Prepares the dialog to allow the user to add an item to the workflow - * package - * - * @param event The event - */ - public void prepareForAdd(ActionEvent event) - { - this.isItemBeingAdded = true; - } - - /** - * Cancels the adding of an item to the workflow package - * - * @param event The event - */ - public void cancelAddPackageItems(ActionEvent event) - { - this.isItemBeingAdded = false; - } - - /** - * Adds an item to the workflow package - * - * @param event The event - */ - public void addPackageItems(ActionEvent event) - { - if (this.itemsToAdd != null) - { - if (this.packageItemsToAdd == null) - { - // create the list of items to add if necessary - this.packageItemsToAdd = new ArrayList(this.itemsToAdd.length); - } - - for (String item : this.itemsToAdd) - { - // if this item is in the remove list it means it was there - // originally - // and has now been re-added, as a result we don't need to do - // anything - // to the original workflow package, therefore remove from the - // remove list - if (this.packageItemsToRemove != null && this.packageItemsToRemove.contains(item)) - { - this.packageItemsToRemove.remove(item); - - if (LOGGER.isDebugEnabled()) - LOGGER.debug("Removed item from the removed list: " + item); - } - else - { - this.packageItemsToAdd.add(item); - - if (LOGGER.isDebugEnabled()) - LOGGER.debug("Added item to the added list: " + item); - } - } - - // reset the rich list so it re-renders - this.packageItemsRichList.setValue(null); - } - - this.isItemBeingAdded = false; - this.itemsToAdd = null; - } - - /** - * Removes an item from the workflow package - * - * @param event The event containing a reference to the item to remove - */ - public void removePackageItem(ActionEvent event) - { - UIActionLink link = (UIActionLink) event.getComponent(); - Map params = link.getParameterMap(); - String nodeRef = new NodeRef(Repository.getStoreRef(), params.get("id")).toString(); - - if (this.packageItemsToAdd != null && this.packageItemsToAdd.contains(nodeRef)) - { - // remove the item from the added list if it was added in this - // dialog session - this.packageItemsToAdd.remove(nodeRef); - - if (LOGGER.isDebugEnabled()) - LOGGER.debug("Removed item from the added list: " + nodeRef); - } - else - { - // add the node to the list of items to remove - if (this.packageItemsToRemove == null) - { - this.packageItemsToRemove = new ArrayList(1); - } - - this.packageItemsToRemove.add(nodeRef); - - if (LOGGER.isDebugEnabled()) - LOGGER.debug("Added item to the removed list: " + nodeRef); - } - - // reset the rich list so it re-renders - this.packageItemsRichList.setValue(null); - } - - /** - * Toggles the complete flag for a workflow package item - * - * @param event The event containing a reference to the item to toggle the - * status for - */ - public void togglePackageItemComplete(ActionEvent event) - { - // TODO: not supported yet - } - - // ------------------------------------------------------------------------------ - // Bean Getters and Setters - - /** - * Returns a String array of NodeRef's that are being added to the workflow - * package - * - * @return String array of NodeRef's - */ - public String[] getItemsToAdd() - { - return this.itemsToAdd; - } - - /** - * Sets the NodeRef's to add as items to the workflow package - * - * @param itemsToAdd NodeRef's to add to the workflow package - */ - public void setItemsToAdd(String[] itemsToAdd) - { - this.itemsToAdd = itemsToAdd; - } - - /** - * Determines whether an item is currently being added to the workflow - * package - * - * @return true if an item is being added - */ - public boolean isItemBeingAdded() - { - return this.isItemBeingAdded; - } - - /** - * Sets the rich list being used for the workflow package items - * - * @param richList The rich list instance - */ - public void setPackageItemsRichList(UIRichList richList) - { - this.packageItemsRichList = richList; - } - - /** - * Returns the rich list being used for the workflow package items - * - * @return The rich list instance - */ - public UIRichList getPackageItemsRichList() - { - return this.packageItemsRichList; - } - - /** - * Returns the Node representing the task - * - * @return The node - */ - public Node getTaskNode() - { - return this.taskNode; - } - - /** - * Returns whether this is a pooled task - * - * @return true => pooled - */ - public boolean isPooledTask() - { - List pooledActors = (List) taskNode.getAssociations().get(WorkflowModel.ASSOC_POOLED_ACTORS); - return (pooledActors != null && pooledActors.size() > 0); - } - - /** - * Returns the WorkflowInstance that the current task belongs to - * - * @return The workflow instance - */ - public WorkflowInstance getWorkflowInstance() - { - if (workflowInstance == null) - { - workflowInstance = getWorkflowTask().path.instance; - } - return this.workflowInstance; - } - - /** - * Returns the URL to the Workflow Definition Image of the current task - * - * @return the url - */ - public String getWorkflowDefinitionImageUrl() - { - return "/workflowdefinitionimage/" + this.getWorkflowInstance().definition.id; - } - - /** - * Returns the action group the current task uses for the workflow package - * - * @return action group id - */ - public String getPackageActionGroup() - { - return (String) this.getWorkflowTask().properties.get(WorkflowModel.PROP_PACKAGE_ACTION_GROUP); - } - - /** - * Returns the action group the current task uses for each workflow package - * item - * - * @return action group id - */ - public String getPackageItemActionGroup() - { - return (String) this.getWorkflowTask().properties.get(WorkflowModel.PROP_PACKAGE_ITEM_ACTION_GROUP); - } - - /** - * Returns a list of resources associated with this task i.e. the children - * of the workflow package - * - * @return The list of nodes - */ - public List getResources() - { - this.resources = new ArrayList(4); - - if (this.workflowPackage != null) - { - UserTransaction tx = null; - try - { - FacesContext context = FacesContext.getCurrentInstance(); - tx = Repository.getUserTransaction(context, true); - tx.begin(); - - List contents = this.workflowService.getPackageContents(getWorkflowTask().id); - - for (NodeRef nodeRef : contents) - { - if (this.getNodeService().exists(nodeRef)) - { - // find it's type so we can see if it's a node we - // are interested in - QName type = this.getNodeService().getType(nodeRef); - - // make sure the type is defined in the data - // dictionary - if (this.getDictionaryService().getType(type) != null) - { - // look for content nodes or links to content - // NOTE: folders within workflow packages are - // ignored for now - if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_CONTENT) - || ApplicationModel.TYPE_FILELINK.equals(type)) - { - // if the node is not in the removed list - // then add create the - // client side representation and add to the - // list - if (this.packageItemsToRemove == null - || this.packageItemsToRemove.contains(nodeRef.toString()) == false) - { - createAndAddNode(nodeRef); - } - } - } - } - } - - // now iterate through the items to add list and add them to the - // list of resources - if (this.packageItemsToAdd != null) - { - for (String newItem : this.packageItemsToAdd) - { - NodeRef nodeRef = new NodeRef(newItem); - if (this.getNodeService().exists(nodeRef)) - { - // we know the type is correct as this was added as - // a result of a query - // for all content items so just add the item to the - // resources list - createAndAddNode(nodeRef); - } - else - { - if (LOGGER.isDebugEnabled()) - LOGGER.debug("Ignoring " + nodeRef + " as it has been removed from the repository"); - } - } - } - - // commit the transaction - tx.commit(); - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), - Repository.ERROR_GENERIC), err.getMessage()), err); - this.resources = Collections. emptyList(); - try - { - if (tx != null) - { - tx.rollback(); - } - } - catch (Exception tex) - { - } - } - } - else if (LOGGER.isDebugEnabled()) - { - LOGGER.debug("Failed to find workflow package for task: " + this.getWorkflowTask().id); - } - - return this.resources; - } - - /** - * Sets the workflow service to use - * - * @param workflowService WorkflowService instance - */ - public void setWorkflowService(WorkflowService workflowService) - { - this.workflowService = workflowService; - } - - protected WorkflowService getWorkflowService() - { - if (workflowService == null) - { - workflowService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getWorkflowService(); - } - return workflowService; - } - - protected WorkflowTask getWorkflowTask() - { - if (task == null) - { - String taskId = this.parameters.get("id"); - task = this.getWorkflowService().getTaskById(taskId); - } - return task; - } - - protected WorkflowTransition[] getWorkflowTransitions() - { - if (transitions == null) - { - transitions = getWorkflowTask().path.node.transitions; - } - return transitions; - } - - // ------------------------------------------------------------------------------ - // Helper methods - - protected void createAndAddNode(NodeRef nodeRef) - { - // create our Node representation - MapNode node = new MapNode(nodeRef, this.getNodeService(), true); - this.browseBean.setupCommonBindingProperties(node); - - // add property resolvers to show path information - node.addPropertyResolver("path", this.browseBean.resolverPath); - node.addPropertyResolver("displayPath", this.browseBean.resolverDisplayPath); - - // add a property resolver to indicate whether the item has been - // completed or not - // node.addPropertyResolver("completed", this.completeResolver); - - // add the id of the task being managed - node.getProperties().put("taskId", this.getWorkflowTask().id); - - this.resources.add(node); - } - - protected void updateResources() - { - // remove any items the user selected to remove - if (this.workflowPackage != null && this.packageItemsToRemove != null && this.packageItemsToRemove.size() > 0) - { - for (String removedItem : this.packageItemsToRemove) - { - this.getNodeService().removeChild(this.workflowPackage, new NodeRef(removedItem)); - } - } - - // add any items the user selected to add - if (this.workflowPackage != null && this.packageItemsToAdd != null && this.packageItemsToAdd.size() > 0) - { - for (String addedItem : this.packageItemsToAdd) - { - NodeRef addedNodeRef = new NodeRef(addedItem); - this.getNodeService().addChild( - this.workflowPackage, - addedNodeRef, - WorkflowModel.ASSOC_PACKAGE_CONTAINS, - QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, QName - .createValidLocalName((String) this.getNodeService().getProperty(addedNodeRef, - ContentModel.PROP_NAME)))); - } - } - } - - // ------------------------------------------------------------------------------ - // Inner classes - - /** - * Property resolver to determine if the given node has been flagged as - * complete - */ - protected class TaskCompleteResolver implements NodePropertyResolver - { - private static final long serialVersionUID = 5862037943275638314L; - - public Object get(Node node) - { - String result = Application.getMessage(FacesContext.getCurrentInstance(), "no"); - List completedItems = (List) getWorkflowTask().properties.get(WorkflowModel.PROP_COMPLETED_ITEMS); - if (completedItems != null && completedItems.size() > 0 && completedItems.contains(node.getNodeRef())) - { - result = Application.getMessage(FacesContext.getCurrentInstance(), "yes"); - } - return result; - } - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/workflow/ReassignTaskDialog.java b/war/src/main/java/org/alfresco/web/bean/workflow/ReassignTaskDialog.java deleted file mode 100644 index 261ac1f913..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/workflow/ReassignTaskDialog.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.workflow; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.ui.common.component.UIGenericPicker; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean implementation for the "Reassign Task" dialog - * - * @author gavinc - */ -public class ReassignTaskDialog extends BaseReassignDialog -{ - private static final long serialVersionUID = 5804171557325189475L; - - protected String taskId; - - private static final Log logger = LogFactory.getLog(ReassignTaskDialog.class); - - - // ------------------------------------------------------------------------------ - // Dialog implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - this.taskId = this.parameters.get("id"); - if (this.taskId == null || this.taskId.length() == 0) - { - throw new IllegalArgumentException("Reassign task dialog called without task id"); - } - } - - @Override - protected String finishImpl(FacesContext context, String outcome) - throws Exception - { - if (logger.isDebugEnabled()) - logger.debug("Reassigning task with id: " + this.taskId); - - UIComponent picker = context.getViewRoot().findComponent("dialog:dialog-body:user-picker"); - - if (picker != null && picker instanceof UIGenericPicker) - { - UIGenericPicker userPicker = (UIGenericPicker)picker; - String[] user = userPicker.getSelectedResults(); - if (user != null && user.length > 0) - { - // create a map to hold the new owner property then update the task - String userName = user[0]; - Map params = new HashMap(1); - params.put(ContentModel.PROP_OWNER, userName); - this.getWorkflowService().updateTask(this.taskId, params, null, null); - } - else - { - if (logger.isWarnEnabled()) - logger.warn("Failed to find selected user, reassign was unsuccessful"); - } - } - else - { - if (logger.isWarnEnabled()) - logger.warn("Failed to find user-picker component, reassign was unsuccessful"); - } - - if (logger.isDebugEnabled()) - logger.debug("Reassigning task with id: " + this.taskId); - - return outcome; - } - - @Override - protected String getErrorMessageId() - { - return "error_reassign_task"; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/workflow/ReassignWorkItemDialog.java b/war/src/main/java/org/alfresco/web/bean/workflow/ReassignWorkItemDialog.java deleted file mode 100644 index bacb01fb7a..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/workflow/ReassignWorkItemDialog.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.workflow; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.ui.common.component.UIGenericPicker; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Bean implementation for the "Reassign Work Item" dialog - * - * @author gavinc - */ -public class ReassignWorkItemDialog extends BaseReassignDialog -{ - private static final long serialVersionUID = 6501900045849920148L; - - protected String workItemId; - - private static final Log logger = LogFactory.getLog(ReassignWorkItemDialog.class); - - - // ------------------------------------------------------------------------------ - // Dialog implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - this.workItemId = this.parameters.get("workitem-id"); - if (this.workItemId == null || this.workItemId.length() == 0) - { - throw new IllegalArgumentException("Reassign workitem dialog called without task id"); - } - } - - @Override - protected String finishImpl(FacesContext context, String outcome) - throws Exception - { - if (logger.isDebugEnabled()) - logger.debug("Reassigning work item with id: " + this.workItemId); - - UIComponent picker = context.getViewRoot().findComponent("dialog:dialog-body:user-picker"); - - if (picker != null && picker instanceof UIGenericPicker) - { - UIGenericPicker userPicker = (UIGenericPicker)picker; - String[] user = userPicker.getSelectedResults(); - if (user != null && user.length > 0) - { - // create a map to hold the new owner property then update the task - String userName = user[0]; - Map params = new HashMap(1); - params.put(ContentModel.PROP_OWNER, userName); - this.getWorkflowService().updateTask(this.workItemId, params, null, null); - } - else - { - if (logger.isWarnEnabled()) - logger.warn("Failed to find selected user, reassign was unsuccessful"); - } - } - else - { - if (logger.isWarnEnabled()) - logger.warn("Failed to find user-picker component, reassign was unsuccessful"); - } - - if (logger.isDebugEnabled()) - logger.debug("Reassigning work item with id: " + this.workItemId); - - return outcome; - } - - @Override - protected String getErrorMessageId() - { - return "error_reassign_workitem"; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/workflow/StartWorkflowWizard.java b/war/src/main/java/org/alfresco/web/bean/workflow/StartWorkflowWizard.java deleted file mode 100644 index 2b0cbd8f55..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/workflow/StartWorkflowWizard.java +++ /dev/null @@ -1,816 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.workflow; - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.ResourceBundle; -import java.util.StringTokenizer; - -import javax.faces.context.FacesContext; -import javax.faces.event.AbortProcessingException; -import javax.faces.event.ActionEvent; -import javax.faces.model.SelectItem; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.policy.BehaviourFilter; -import org.alfresco.repo.workflow.WorkflowModel; -import org.alfresco.repo.workflow.activiti.ActivitiConstants; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.cmr.invitation.InvitationService; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.workflow.WorkflowDefinition; -import org.alfresco.service.cmr.workflow.WorkflowPath; -import org.alfresco.service.cmr.workflow.WorkflowService; -import org.alfresco.service.cmr.workflow.WorkflowTask; -import org.alfresco.service.cmr.workflow.WorkflowTaskDefinition; -import org.alfresco.service.cmr.workflow.WorkflowTaskState; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.servlet.FacesHelper; -import org.alfresco.web.bean.repository.MapNode; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.repository.TransientNode; -import org.alfresco.web.bean.wizard.BaseWizardBean; -import org.alfresco.web.data.IDataContainer; -import org.alfresco.web.data.QuickSort; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.alfresco.web.ui.common.component.data.UIRichList; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.extensions.config.ConfigElement; - -/** - * Bean implementation for the Start Workflow Wizard. - * - * @author gavinc - */ -public class StartWorkflowWizard extends BaseWizardBean -{ - private static final long serialVersionUID = -4370844066621902880L; - - protected String selectedWorkflow; - protected String previouslySelectedWorkflow; - - transient protected List availableWorkflows; - transient private Map workflows; - - protected List excludedWorkflows; - protected List invitationWorkflows; - - transient private WorkflowService workflowService; - transient private InvitationService invitationService; - transient private BehaviourFilter policyBehaviourFilter; - - protected Node startTaskNode; - protected List resources; - protected List packageItemsToAdd; - protected UIRichList packageItemsRichList; - protected String[] itemsToAdd; - protected boolean isItemBeingAdded = false; - protected boolean nextButtonDisabled = false; - - transient private NodeService unprotectedNodeService; - - private static final Log logger = LogFactory.getLog(StartWorkflowWizard.class); - - public void setUnprotectedNodeService(NodeService unprotectedNodeService) - { - this.unprotectedNodeService = unprotectedNodeService; - } - - protected NodeService getUnprotectedNodeService() - { - if (this.unprotectedNodeService == null) - { - this.unprotectedNodeService = (NodeService) FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), "nodeService"); - } - return this.unprotectedNodeService; - } - - public void setPolicyBehaviourFilter(BehaviourFilter policyBehaviourFilter) - { - this.policyBehaviourFilter = policyBehaviourFilter; - } - - protected BehaviourFilter getBehaviourFilter() - { - if(this.policyBehaviourFilter == null) - { - this.policyBehaviourFilter = (BehaviourFilter) FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), "policyBehaviourFilter"); - } - return this.policyBehaviourFilter; - } - - protected Map getWorkflows() - { - if (this.workflows == null) - { - initializeWorkflows(); - } - return this.workflows; - } - - // ------------------------------------------------------------------------------ - // Wizard implementation - - @Override - public void init(Map parameters) - { - super.init(parameters); - - // reset the selected workflow - if (this.availableWorkflows != null && this.availableWorkflows.size() > 0) - { - this.selectedWorkflow = (String)this.availableWorkflows.get(0).getValue(); - } - else - { - this.selectedWorkflow = null; - } - - this.previouslySelectedWorkflow = null; - this.startTaskNode = null; - this.resources = null; - this.itemsToAdd = null; - this.packageItemsToAdd = new ArrayList(); - this.isItemBeingAdded = false; - resetRichList(); - - // add the item the workflow wizard was started on to the list of resources - String itemToWorkflowId = this.parameters.get("item-to-workflow"); - try - { - if (itemToWorkflowId != null && itemToWorkflowId.length() > 0) - { - // create the node ref for the item and determine its type - NodeRef itemToWorkflow = new NodeRef(Repository.getStoreRef(), itemToWorkflowId); - QName type = this.getNodeService().getType(itemToWorkflow); - - if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_CONTENT) || this.getDictionaryService().isSubClass(type, ApplicationModel.TYPE_FILELINK)) - { - this.packageItemsToAdd.add(itemToWorkflow.toString()); - } - } - } - catch (InvalidNodeRefException refErr) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] { itemToWorkflowId })); - throw new AbortProcessingException("Invalid node reference"); - } - } - - @Override - public void restored() - { - // reset the workflow package rich list so everything gets re-evaluated - resetRichList(); - } - - @Override - protected String finishImpl(FacesContext context, String outcome) - throws Exception - { - // TODO: Deal with workflows that don't require any data - - if (logger.isDebugEnabled()) - logger.debug("Starting workflow: " + this.selectedWorkflow); - - // prepare the parameters from the current state of the property sheet - Map params = WorkflowUtil.prepareTaskParams(this.startTaskNode); - - if (logger.isDebugEnabled()) - logger.debug("Starting workflow with parameters: " + params); - - // create a workflow package for the attached items and add them - NodeRef workflowPackage = this.getWorkflowService().createPackage(null); - params.put(WorkflowModel.ASSOC_PACKAGE, workflowPackage); - - for (String addedItem : this.packageItemsToAdd) - { - NodeRef addedNodeRef = new NodeRef(addedItem); - //MNT-11522. fix bug. add behavior filter for add items in workflow package. - try - { - this.getBehaviourFilter().disableBehaviour(addedNodeRef, ContentModel.ASPECT_AUDITABLE); - this.getUnprotectedNodeService().addChild(workflowPackage, addedNodeRef, - WorkflowModel.ASSOC_PACKAGE_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, - QName.createValidLocalName((String)this.getNodeService().getProperty( - addedNodeRef, ContentModel.PROP_NAME)))); - } - finally - { - this.getBehaviourFilter().enableBehaviour(addedNodeRef, ContentModel.ASPECT_AUDITABLE); - } - } - - // setup the context for the workflow (this is the space the workflow was launched from) - Node workflowContext = this.navigator.getCurrentNode(); - if (workflowContext != null) - { - params.put(WorkflowModel.PROP_CONTEXT, (Serializable)workflowContext.getNodeRef()); - } - - // start the workflow to get access to the start task - WorkflowPath path = this.getWorkflowService().startWorkflow(this.selectedWorkflow, params); - if (path != null) - { - // extract the start task - List tasks = this.getWorkflowService().getTasksForWorkflowPath(path.id); - if (tasks.size() == 1) - { - WorkflowTask startTask = tasks.get(0); - - if (logger.isDebugEnabled()) - logger.debug("Found start task:" + startTask); - - if (startTask.state == WorkflowTaskState.IN_PROGRESS) - { - // end the start task to trigger the first 'proper' - // task in the workflow - this.getWorkflowService().endTask(startTask.id, null); - } - } - - if (logger.isDebugEnabled()) - logger.debug("Started workflow: " + this.selectedWorkflow); - } - - return outcome; - } - - @Override - public String next() - { - String stepName = Application.getWizardManager().getCurrentStepName(); - - if ("options".equals(stepName) && - (this.selectedWorkflow.equals(this.previouslySelectedWorkflow) == false)) - { - // retrieve the start task for the selected workflow, get the task - // definition and create a transient node to allow the property - // sheet to collect the required data. - - WorkflowDefinition flowDef = this.getWorkflows().get(this.selectedWorkflow); - - if (logger.isDebugEnabled()) - logger.debug("Selected workflow: "+ flowDef); - - WorkflowTaskDefinition taskDef = flowDef.getStartTaskDefinition(); - if (taskDef != null) - { - if (logger.isDebugEnabled()) - logger.debug("Start task definition: " + taskDef); - - // create an instance of a task from the data dictionary - this.startTaskNode = TransientNode.createNew(getDictionaryService(), taskDef.metadata, - "task_" + System.currentTimeMillis(), null); - } - - // we also need to reset the resources list so that the actions get re-evaluated - resetRichList(); - } - - return null; - } - - @Override - public String back() - { - String stepName = Application.getWizardManager().getCurrentStepName(); - - // if we have come back to the "choose-workflow" step remember - // the current workflow selection - if ("choose-workflow".equals(stepName)) - { - this.previouslySelectedWorkflow = this.selectedWorkflow; - } - - return null; - } - - @Override - public boolean getNextButtonDisabled() - { - return this.nextButtonDisabled; - } - - @Override - public String getContainerTitle() - { - String wizTitle = null; - - ResourceBundle bundle = Application.getBundle(FacesContext.getCurrentInstance()); - String stepName = Application.getWizardManager().getCurrentStepName(); - - if ("choose-workflow".equals(stepName) == false && this.selectedWorkflow != null) - { - String titlePattern = bundle.getString("start_named_workflow_wizard"); - WorkflowDefinition workflowDef = this.getWorkflows().get(this.selectedWorkflow); - wizTitle = MessageFormat.format(titlePattern, new Object[] {workflowDef.title}); - } - else - { - wizTitle = bundle.getString("start_workflow_wizard"); - } - - return wizTitle; - } - - // ------------------------------------------------------------------------------ - // Event Handlers - - /** - * Prepares the dialog to allow the user to add an item to the workflow package - * - * @param event The event - */ - public void prepareForAdd(ActionEvent event) - { - this.isItemBeingAdded = true; - } - - /** - * Cancels the adding of an item to the workflow package - * - * @param event The event - */ - public void cancelAddPackageItems(ActionEvent event) - { - this.isItemBeingAdded = false; - } - - /** - * Adds items to the workflow package - * - * @param event The event - */ - public void addPackageItems(ActionEvent event) - { - if (this.itemsToAdd != null) - { - for (String item : this.itemsToAdd) - { - this.packageItemsToAdd.add(item); - - if (logger.isDebugEnabled()) - logger.debug("Added item to the added list: " + item); - } - - // reset the rich list so it re-renders - this.packageItemsRichList.setValue(null); - } - - this.isItemBeingAdded = false; - this.itemsToAdd = null; - } - - /** - * Removes an item from the workflow package - * - * @param event The event containing a reference to the item to remove - */ - public void removePackageItem(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String nodeRef = new NodeRef(Repository.getStoreRef(), params.get("id")).toString(); - - if (this.packageItemsToAdd.contains(nodeRef)) - { - // remove the item from the added list if it was added in this dialog session - this.packageItemsToAdd.remove(nodeRef); - - if (logger.isDebugEnabled()) - logger.debug("Removed item from the added list: " + nodeRef); - } - - // reset the rich list so it re-renders - this.packageItemsRichList.setValue(null); - } - - // ------------------------------------------------------------------------------ - // Bean Getters and Setters - - /** - * Returns a String array of NodeRef's that are being added to the workflow package - * - * @return String array of NodeRef's - */ - public String[] getItemsToAdd() - { - return this.itemsToAdd; - } - - /** - * Sets the NodeRef's to add as items to the workflow package - * - * @param itemsToAdd NodeRef's to add to the workflow package - */ - public void setItemsToAdd(String[] itemsToAdd) - { - this.itemsToAdd = itemsToAdd; - } - - /** - * Determines whether an item is currently being added to the workflow package - * - * @return true if an item is being added - */ - public boolean isItemBeingAdded() - { - return this.isItemBeingAdded; - } - - /** - * Sets the rich list being used for the workflow package items - * - * @param richList The rich list instance - */ - public void setPackageItemsRichList(UIRichList richList) - { - this.packageItemsRichList = richList; - } - - /** - * Returns the rich list being used for the workflow package items - * - * @return The rich list instance - */ - public UIRichList getPackageItemsRichList() - { - return this.packageItemsRichList; - } - - /** - * Returns the workflow selected by the user - * - * @return The selected workflow - */ - public String getSelectedWorkflow() - { - return selectedWorkflow; - } - - /** - * Sets the selected workflow - * - * @param selectedWorkflow The workflow selected - */ - public void setSelectedWorkflow(String selectedWorkflow) - { - this.selectedWorkflow = selectedWorkflow; - } - - /** - * Returns the Node representing the start task metadata required - * - * @return The Node for the start task - */ - public Node getTaskMetadataNode() - { - return this.startTaskNode; - } - - /** - * Returns the action group the current task uses for the workflow package - * - * @return action group id - */ - public String getPackageActionGroup() - { - String actionGroup = null; - - WorkflowDefinition flowDef = this.getWorkflows().get(this.selectedWorkflow); - WorkflowTaskDefinition taskDef = flowDef.getStartTaskDefinition(); - if (taskDef != null) - { - PropertyDefinition propDef = taskDef.metadata.getProperties().get( - WorkflowModel.PROP_PACKAGE_ACTION_GROUP); - if (propDef != null) - { - actionGroup = propDef.getDefaultValue(); - } - } - - return actionGroup; - } - - /** - * Returns the action group the current task uses for each workflow package item - * - * @return action group id - */ - public String getPackageItemActionGroup() - { - String actionGroup = null; - - WorkflowDefinition flowDef = this.getWorkflows().get(this.selectedWorkflow); - WorkflowTaskDefinition taskDef = flowDef.getStartTaskDefinition(); - if (taskDef != null) - { - PropertyDefinition propDef = taskDef.metadata.getProperties().get( - WorkflowModel.PROP_PACKAGE_ITEM_ACTION_GROUP); - if (propDef != null) - { - actionGroup = propDef.getDefaultValue(); - } - } - - return actionGroup; - } - - /** - * @return Returns the summary data for the wizard. - */ - public String getSummary() - { - ResourceBundle bundle = Application.getBundle(FacesContext.getCurrentInstance()); - - String workflowName = null; - for (SelectItem item : this.availableWorkflows) - { - if (item.getValue().equals(this.selectedWorkflow)) - { - workflowName = item.getLabel(); - break; - } - } - - return buildSummary( - new String[] {bundle.getString("start_workflow")}, - new String[] {workflowName}); - } - - /** - * Determines whether there are any workflows to start - * - * @return true if there are startable workflows - */ - public boolean getHasStartableWorkflows() - { - // get the list of startable workflow, this will intialise the list if necessary - List workflows = getStartableWorkflows(); - return (workflows.size() > 0); - } - - private void initializeWorkflows() - { - // NOTE: we don't cache the list of startable workflows as they could get - // updated, in which case we need the latest instance id, they could - // theoretically also get removed. - - this.availableWorkflows = new ArrayList(4); - this.workflows = new HashMap(4); - - List configuredInvitationWorkflows = this.getInvitationServiceWorkflowNames(); - List excludedWorkflows = this.getExcludedWorkflows(); - - List workflowDefs = this.getWorkflowService().getDefinitions(); - for (WorkflowDefinition workflowDef : workflowDefs) - { - String name = workflowDef.name; - - if (configuredInvitationWorkflows.contains(name) == false && - excludedWorkflows.contains(name) == false) - { - // add the workflow if it is not a WCM specific workflow - String label = workflowDef.title; - if (workflowDef.description != null && workflowDef.description.length() > 0) - { - label = label + " (" + workflowDef.description + ")"; - } - this.availableWorkflows.add(new SelectItem(workflowDef.id, label)); - this.workflows.put(workflowDef.id, workflowDef); - } - } - - // disable the next button if there are no workflows - if (this.availableWorkflows.size() == 0) - { - this.nextButtonDisabled = true; - } - } - - /** - * Returns a list of workflows that can be started. - * - * @return List of SelectItem objects representing the workflows - */ - public List getStartableWorkflows() - { - if (availableWorkflows == null) - { - initializeWorkflows(); - } - - // Alphabetical list sorting - // Fix bug reported in https://issues.alfresco.com/browse/ETWOTWO-302 - - QuickSort sorter = new QuickSort(availableWorkflows, "label", true, IDataContainer.SORT_CASEINSENSITIVE); - sorter.sort(); - - // select the first workflow in the list - if (this.availableWorkflows.size() > 0 && previouslySelectedWorkflow == null) - { - this.selectedWorkflow = (String)this.availableWorkflows.get(0).getValue(); - } - - return availableWorkflows; - } - - /** - * Returns the URL to the Workflow Definition Image of the current task - * - * @return the url - */ - public String getWorkflowDefinitionImageUrl() - { - String url = null; - if (selectedWorkflow != null) - { - WorkflowDefinition def = getWorkflows().get(selectedWorkflow); - url = "/workflowdefinitionimage/" + def.id; - } - return url; - } - - /** - * Returns a list of resources associated with this task - * i.e. the children of the workflow package - * - * @return The list of nodes - */ - public List getResources() - { - this.resources = new ArrayList(4); - - UserTransaction tx = null; - try - { - FacesContext context = FacesContext.getCurrentInstance(); - tx = Repository.getUserTransaction(context, true); - tx.begin(); - - for (String newItem : this.packageItemsToAdd) - { - NodeRef nodeRef = new NodeRef(newItem); - if (this.getNodeService().exists(nodeRef)) - { - // create our Node representation - MapNode node = new MapNode(nodeRef, this.getNodeService(), true); - this.browseBean.setupCommonBindingProperties(node); - - // add property resolvers to show path information - node.addPropertyResolver("path", this.browseBean.resolverPath); - node.addPropertyResolver("displayPath", this.browseBean.resolverDisplayPath); - - this.resources.add(node); - } - else - { - if (logger.isDebugEnabled()) - logger.debug("Ignoring " + nodeRef + " as it has been removed from the repository"); - } - } - - // commit the transaction - tx.commit(); - } - catch (Throwable err) - { - Utils.addErrorMessage(MessageFormat.format(Application.getMessage( - FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err); - this.resources = Collections.emptyList(); - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - - return this.resources; - } - - /** - * Sets the workflow service to use - * - * @param workflowService WorkflowService instance - */ - public void setWorkflowService(WorkflowService workflowService) - { - this.workflowService = workflowService; - } - - - protected WorkflowService getWorkflowService() - { - if (this.workflowService == null) - { - this.workflowService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getWorkflowService(); - } - return this.workflowService; - } - - // ------------------------------------------------------------------------------ - // Helper methods - - /** - * Resets the rich list - */ - protected void resetRichList() - { - if (this.packageItemsRichList != null) - { - this.packageItemsRichList.setValue(null); - this.packageItemsRichList = null; - } - } - - /** - * Get the Names of globally excluded workflow-names. - * - * @return The names of the workflows to exclude. - */ - protected List getExcludedWorkflows() - { - if ((excludedWorkflows == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) - { - FacesContext fc = FacesContext.getCurrentInstance(); - ConfigElement config = Application.getConfigService(fc).getGlobalConfig().getConfigElement("excluded-workflows"); - if (config != null) - { - StringTokenizer t = new StringTokenizer(config.getValue().trim(), ", "); - excludedWorkflows = new ArrayList(t.countTokens()); - while (t.hasMoreTokens()) - { - String wfName = t.nextToken(); - excludedWorkflows.add(wfName); - } - } - else - { - excludedWorkflows = Collections.emptyList(); - } - } - return excludedWorkflows; - } - - /** - * Get the Names of the Invitation Service Workflows - * - * @return The names of the Invitation Service workflows - */ - protected List getInvitationServiceWorkflowNames() - { - if( invitationWorkflows == null ) - { - if (invitationService != null) - { - invitationWorkflows = invitationService.getInvitationServiceWorkflowNames(); - } - } - return invitationWorkflows; - } - - public void setInvitationService(InvitationService invitationService) - { - this.invitationService = invitationService; - } - - public InvitationService getInvitationService() - { - return invitationService; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/workflow/ViewCompletedTaskDialog.java b/war/src/main/java/org/alfresco/web/bean/workflow/ViewCompletedTaskDialog.java deleted file mode 100644 index 5981eb6ad3..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/workflow/ViewCompletedTaskDialog.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.workflow; - -import java.util.List; - -import javax.faces.context.FacesContext; - -import org.alfresco.web.app.Application; -import org.alfresco.web.config.DialogsConfigElement.DialogButtonConfig; - -/** - * Bean implementation for the "View Completed Task" dialog. - * - * @author gavinc - */ -public class ViewCompletedTaskDialog extends ManageTaskDialog -{ - // ------------------------------------------------------------------------------ - // Dialog implementation - - private static final long serialVersionUID = 1568710712589201055L; - - @Override - protected String finishImpl(FacesContext context, String outcome) - throws Exception - { - // nothing to do as the finish button is not shown and the dialog is read only - - return outcome; - } - - @Override - public String getCancelButtonLabel() - { - return Application.getMessage(FacesContext.getCurrentInstance(), "close"); - } - - @Override - public List getAdditionalButtons() - { - return null; - } - - @Override - public String getContainerTitle() - { - String titleStart = Application.getMessage(FacesContext.getCurrentInstance(), "view_completed_task_title"); - - return titleStart + ": " + this.getWorkflowTask().title; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/workflow/WorkflowBean.java b/war/src/main/java/org/alfresco/web/bean/workflow/WorkflowBean.java deleted file mode 100644 index 4ac29e9dfe..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/workflow/WorkflowBean.java +++ /dev/null @@ -1,388 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.workflow; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.transaction.UserTransaction; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.workflow.WorkflowModel; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.workflow.WorkflowService; -import org.alfresco.service.cmr.workflow.WorkflowTask; -import org.alfresco.service.cmr.workflow.WorkflowTaskDefinition; -import org.alfresco.service.cmr.workflow.WorkflowTaskQuery; -import org.alfresco.service.cmr.workflow.WorkflowTaskState; -import org.alfresco.service.cmr.workflow.WorkflowTransition; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.config.ClientConfigElement; -import org.springframework.extensions.surf.util.ParameterCheck; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.NavigationBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.bean.repository.TransientMapNode; -import org.alfresco.web.bean.repository.TransientNode; -import org.alfresco.web.bean.repository.User; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Managed bean used for providing support for the workflow task dashlets - * - * @author gavinc - */ -public class WorkflowBean implements Serializable -{ - private static final long serialVersionUID = 2950475254440425384L; - - protected NavigationBean navigationBean; - - transient private NodeService nodeService; - transient private WorkflowService workflowService; - - protected List tasks; - protected List activeTasks; - protected List pooledTasks; - protected List completedTasks; - - private static final Log logger = LogFactory.getLog(WorkflowBean.class); - - public static final String BEAN_NAME = "WorkflowBean"; - - - // ------------------------------------------------------------------------------ - // Bean Getters and Setters - - /** - * Returns a list of nodes representing the "all" active tasks. - * - * @return List of all active tasks - */ - public List getAllActiveTasks() - { - if (this.activeTasks == null) - { - // get the current username - FacesContext context = FacesContext.getCurrentInstance(); - User user = Application.getCurrentUser(context); - String userName = user.getUserName(); - - UserTransaction tx = null; - try - { - tx = Repository.getUserTransaction(context, true); - tx.begin(); - - // query for all active tasks - WorkflowTaskQuery query = new WorkflowTaskQuery(); - List tasks = this.getWorkflowService().queryTasks(query); - - // create a list of transient nodes to represent - this.activeTasks = new ArrayList(tasks.size()); - for (WorkflowTask task : tasks) - { - Node node = createTask(task); - this.activeTasks.add(node); - - if (logger.isDebugEnabled()) - logger.debug("Added active task: " + node); - } - - // commit the changes - tx.commit(); - } - catch (Throwable e) - { - // rollback the transaction - try { if (tx != null) {tx.rollback();} } catch (Exception ex) {} - Utils.addErrorMessage("Failed to get all active tasks: " + e.toString(), e); - } - } - - return this.activeTasks; - } - - /** - * Returns a list of nodes representing the "pooled" to do tasks the - * current user has. - * - * @return List of to do tasks - */ - public List getPooledTasks() - { - if (this.pooledTasks == null) - { - // get the current username - FacesContext context = FacesContext.getCurrentInstance(); - User user = Application.getCurrentUser(context); - String userName = user.getUserName(); - - UserTransaction tx = null; - try - { - tx = Repository.getUserTransaction(context, true); - tx.begin(); - - // get the current pooled tasks for the current user - List tasks = this.getWorkflowService().getPooledTasks(userName, true); - - // create a list of transient nodes to represent - this.pooledTasks = new ArrayList(tasks.size()); - for (WorkflowTask task : tasks) - { - Node node = createTask(task); - this.pooledTasks.add(node); - - if (logger.isDebugEnabled()) - logger.debug("Added pooled task: " + node); - } - - // commit the changes - tx.commit(); - } - catch (Throwable e) - { - // rollback the transaction - try { if (tx != null) {tx.rollback();} } catch (Exception ex) {} - Utils.addErrorMessage("Failed to get pooled tasks: " + e.toString(), e); - } - } - - return this.pooledTasks; - } - - /** - * Returns a list of nodes representing the to do tasks the - * current user has. - * - * @return List of to do tasks - */ - public List getTasksToDo() - { - if (this.tasks == null) - { - // get the current username - FacesContext context = FacesContext.getCurrentInstance(); - User user = Application.getCurrentUser(context); - String userName = user.getUserName(); - - UserTransaction tx = null; - try - { - tx = Repository.getUserTransaction(context, true); - tx.begin(); - - // get the current in progress tasks for the current user - List tasks = this.getWorkflowService().getAssignedTasks( - userName, WorkflowTaskState.IN_PROGRESS, true); - - // create a list of transient nodes to represent - this.tasks = new ArrayList(tasks.size()); - for (WorkflowTask task : tasks) - { - Node node = createTask(task); - this.tasks.add(node); - - if (logger.isDebugEnabled()) - logger.debug("Added to do task: " + node); - } - - // commit the changes - tx.commit(); - } - catch (Throwable e) - { - // rollback the transaction - try { if (tx != null) {tx.rollback();} } catch (Exception ex) {} - Utils.addErrorMessage("Failed to get to do tasks: " + e.toString(), e); - } - } - - return this.tasks; - } - - /** - * Returns a list of nodes representing the completed tasks the - * current user has. - * - * @return List of completed tasks - */ - public List getTasksCompleted() - { - if (this.completedTasks == null) - { - // get the current username - FacesContext context = FacesContext.getCurrentInstance(); - User user = Application.getCurrentUser(context); - String userName = user.getUserName(); - - UserTransaction tx = null; - try - { - tx = Repository.getUserTransaction(context, true); - tx.begin(); - - // get the current in progress tasks for the current user - ClientConfigElement clientConfig = (ClientConfigElement)Application.getConfigService(context).getGlobalConfig().getConfigElement( - ClientConfigElement.CONFIG_ELEMENT_ID); - WorkflowTaskQuery query = new WorkflowTaskQuery(); - query.setActive(null); - query.setActorId(userName); - query.setTaskState(WorkflowTaskState.COMPLETED); - query.setLimit(clientConfig.getTasksCompletedMaxResults()); - List tasks = this.getWorkflowService().queryTasks(query); - - // create a list of transient nodes to represent - this.completedTasks = new ArrayList(tasks.size()); - for (WorkflowTask task : tasks) - { - Node node = createTask(task); - this.completedTasks.add(node); - - if (logger.isDebugEnabled()) - logger.debug("Added completed task: " + node); - } - - // commit the changes - tx.commit(); - } - catch (Throwable e) - { - // rollback the transaction - try { if (tx != null) {tx.rollback();} } catch (Exception ex) {} - Utils.addErrorMessage("Failed to get completed tasks: " + e.toString(), e); - } - } - - return this.completedTasks; - } - - /** - * Sets the navigation bean to use - * - * @param navigationBean The NavigationBean to set. - */ - public void setNavigationBean(NavigationBean navigationBean) - { - this.navigationBean = navigationBean; - } - - /** - * Sets the workflow service to use - * - * @param workflowService WorkflowService instance - */ - public void setWorkflowService(WorkflowService workflowService) - { - this.workflowService = workflowService; - } - - protected WorkflowService getWorkflowService() - { - if (this.workflowService == null) - { - this.workflowService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getWorkflowService(); - } - return this.workflowService; - } - - /** - * Sets the node service to use - * - * @param nodeService NodeService instance - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - protected NodeService getNodeService() - { - if (this.nodeService == null) - { - this.nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService(); - } - return this.nodeService; - } - // ------------------------------------------------------------------------------ - // Navigation handlers - - public void setupTaskDialog(ActionEvent event) - { - UIActionLink link = (UIActionLink)event.getComponent(); - Map params = link.getParameterMap(); - String id = params.get("id"); - String type = params.get("type"); - - // setup the dispatch context with the task we're opening a dialog for - TransientNode node = new TransientNode(QName.createQName(type), id, null); - this.navigationBean.setupDispatchContext(node); - - // pass on parameters for the dialog - Application.getDialogManager().setupParameters(event); - } - - public void setupTaskDialog(String id, String type) - { - ParameterCheck.mandatoryString("Task ID", id); - ParameterCheck.mandatoryString("Task Type", type); - - // setup the dispatch context with the task we're opening a dialog for - TransientNode node = new TransientNode(QName.createQName(type), id, null); - this.navigationBean.setupDispatchContext(node); - - // pass on parameters for the dialog - Map params = new HashMap(2, 1.0f); - params.put("id", id); - params.put("type", type); - Application.getDialogManager().setupParameters(params); - } - - - // ------------------------------------------------------------------------------ - // Helper methods - - /** - * Creates and populates a TransientNode to represent the given - * workflow task from the repository workflow engine - * - * @param task The task to create a representation of - */ - protected TransientMapNode createTask(WorkflowTask task) - { - return new WorkflowTaskNode(task); - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/workflow/WorkflowConsoleBean.java b/war/src/main/java/org/alfresco/web/bean/workflow/WorkflowConsoleBean.java deleted file mode 100644 index 5690974749..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/workflow/WorkflowConsoleBean.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.workflow; - -import java.io.Serializable; - -import javax.faces.context.FacesContext; - -import org.alfresco.repo.workflow.WorkflowInterpreter; -import org.alfresco.service.cmr.workflow.WorkflowDefinition; -import org.alfresco.web.app.servlet.FacesHelper; - - -/** - * Backing bean to support the Workflow Console - */ -public class WorkflowConsoleBean implements Serializable -{ - private static final long serialVersionUID = -7531838393180855185L; - - // command - private String command = ""; - private String submittedCommand = "none"; - private long duration = 0L; - private String result = null; - - // supporting repository services - transient private WorkflowInterpreter workflowInterpreter; - - - /** - * @param workflowInterpreter workflow interpreter - */ - public void setWorkflowInterpreter(WorkflowInterpreter workflowInterpreter) - { - this.workflowInterpreter = workflowInterpreter; - } - - private WorkflowInterpreter getWorkflowInterpreter() - { - if (this.workflowInterpreter == null) - { - this.workflowInterpreter = (WorkflowInterpreter) FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), "workflowInterpreter"); - } - return this.workflowInterpreter; - } - - /** - * Gets the command result - * - * @return result - */ - public String getResult() - { - if (result == null) - { - interpretCommand("help"); - } - return result; - } - - /** - * Sets the command result - * - * @param result - */ - public void setResult(String result) - { - this.result = result; - } - - /** - * Gets the current query - * - * @return query statement - */ - public String getCommand() - { - return command; - } - - /** - * Set the current command - * - * @param command command - */ - public void setCommand(String command) - { - this.command = command; - } - - /** - * Gets the submitted command - * - * @return submitted command - */ - public String getSubmittedCommand() - { - return submittedCommand; - } - - /** - * Set the submitted command - * - * @param submittedCommand The submitted command - */ - public void setSubmittedCommand(String submittedCommand) - { - this.submittedCommand = submittedCommand; - } - - /** - * Gets the last command duration - * - * @return command duration - */ - public long getDuration() - { - return duration; - } - - /** - * Set the duration - * - * @param duration The duration - */ - public void setDuration(long duration) - { - this.duration = duration; - } - - /** - * Action to submit command - * - * @return next action - */ - public String submitCommand() - { - interpretCommand(command); - return "success"; - } - - /** - * Gets the current user name - * - * @return user name - */ - public String getCurrentUserName() - { - return getWorkflowInterpreter().getCurrentUserName(); - } - - /** - * Gets the current workflow definition - * - * @return workflow definition - */ - public String getCurrentWorkflowDef() - { - WorkflowDefinition def = getWorkflowInterpreter().getCurrentWorkflowDef(); - return (def == null) ? "None" : def.title + " v" + def.version; - } - - /** - * Interpret workflow console command - * - * @param command command - */ - private void interpretCommand(String command) - { - try - { - long startms = System.currentTimeMillis(); - String result = getWorkflowInterpreter().interpretCommand(command); - setDuration(System.currentTimeMillis() - startms); - setResult(result); - setCommand(""); - setSubmittedCommand(command); - } - catch (Exception e) - { - setResult(e.toString()); - } - } - -} diff --git a/war/src/main/java/org/alfresco/web/bean/workflow/WorkflowTaskNode.java b/war/src/main/java/org/alfresco/web/bean/workflow/WorkflowTaskNode.java deleted file mode 100644 index 359d91957c..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/workflow/WorkflowTaskNode.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.workflow; - -import java.util.HashMap; -import java.util.Map; - -import org.alfresco.model.ContentModel; -import org.alfresco.repo.workflow.WorkflowModel; -import org.alfresco.service.cmr.workflow.WorkflowTask; -import org.alfresco.service.cmr.workflow.WorkflowTaskState; -import org.alfresco.service.cmr.workflow.WorkflowTransition; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.TransientMapNode; -import org.springframework.extensions.surf.util.I18NUtil; - -/** - * Wrapper around a {@link WorkflowTask} to allow it to be approached as a {@link Node}. - * Can hold additional properties, on top of the properties in the actual {@link WorkflowTask}. - * - * @author Frederik Heremans - */ -public class WorkflowTaskNode extends TransientMapNode { - - private static final long serialVersionUID = 1L; - private static final String DEFAULT_TRANSITION_TITLE = "bpm_businessprocessmodel.transition.title"; - private Map propertyWrapper; - - private WorkflowTask workflowTask; - - public WorkflowTaskNode(WorkflowTask workflowTask) { - super(workflowTask.getDefinition().getMetadata().getName(), workflowTask.getTitle(), null); - this.workflowTask = workflowTask; - - propertyWrapper = new WorkflowTaskPropertyBackedMap(); - - propertyWrapper.put(ContentModel.PROP_NAME.toString(), workflowTask.getTitle()); - propertyWrapper.put("type", type.toString()); - propertyWrapper.put("id", workflowTask.getId()); - - // add extra properties for completed tasks - if (workflowTask.getState().equals(WorkflowTaskState.COMPLETED)) - { - // add the outcome label for any completed task - String outcome = null; - String transition = (String)workflowTask.getProperties().get(WorkflowModel.PROP_OUTCOME); - if (transition != null) - { - for (WorkflowTransition trans : workflowTask.getDefinition().getNode().getTransitions()) - { - if (trans.getId().equals(transition)) - { - outcome = trans.getTitle(); - break; - } - } - - if(outcome == null) - { - outcome = transition; - } - } - - if (outcome == null) - { - outcome = I18NUtil.getMessage(DEFAULT_TRANSITION_TITLE); - } - propertyWrapper.put("outcome", outcome); - - // add the workflow instance id and name this taks belongs to - propertyWrapper.put("workflowInstanceId", workflowTask.getPath().getInstance().getId()); - - // add the task itself as a property - propertyWrapper.put("workflowTask", workflowTask); - } - - // Add an additional property, containing a human-friendly representation of the priority - Integer priority = (Integer) workflowTask.getProperties().get(WorkflowModel.PROP_PRIORITY); - String priorityMessage = ""; - if (priority != null) - { - priorityMessage = I18NUtil.getMessage(getPriorityMessageKey(priority), I18NUtil.getLocale()); - } - propertyWrapper.put("priorityMessage", priorityMessage); - - } - - @Override - public Map getProperties() { - return propertyWrapper; - } - - /** - * Map which can contain local values (added by put and putAll). Get-operation reverts - * to {@link WorkflowTask} properties when not found in the local values. - * - * @author Frederik Heremans - */ - private class WorkflowTaskPropertyBackedMap extends HashMap - { - private static final long serialVersionUID = 1L; - - @Override - public Object get(Object key) { - String fullKey = QName.resolveToQNameString(WorkflowTaskNode.this.getNamespacePrefixResolver(), key.toString()); - Object value = super.get(fullKey); - if(value == null) - { - value = workflowTask.getProperties().get(QName.resolveToQName(WorkflowTaskNode.this.getNamespacePrefixResolver(), fullKey)); - } - return value; - } - - @Override - public boolean containsKey(Object key) { - String fullKey = QName.resolveToQNameString(WorkflowTaskNode.this.getNamespacePrefixResolver(), key.toString()); - boolean contains = super.containsKey(fullKey); - if(!contains) - { - contains = workflowTask.getProperties().containsKey(QName.resolveToQName(WorkflowTaskNode.this.getNamespacePrefixResolver(), fullKey)); - } - return contains; - } - - @Override - public Object put(String key, Object value) { - return super.put(QName.resolveToQNameString(WorkflowTaskNode.this.getNamespacePrefixResolver(), key.toString()), value); - } - } - - protected String getPriorityMessageKey(int priority) - { - return "listconstraint.bpm_allowedPriority." + priority; - } -} diff --git a/war/src/main/java/org/alfresco/web/bean/workflow/WorkflowUtil.java b/war/src/main/java/org/alfresco/web/bean/workflow/WorkflowUtil.java deleted file mode 100644 index 5a07f83c97..0000000000 --- a/war/src/main/java/org/alfresco/web/bean/workflow/WorkflowUtil.java +++ /dev/null @@ -1,302 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.bean.workflow; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletContext; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.AssociationRef; -import org.alfresco.service.cmr.repository.CopyService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.workflow.WorkflowService; -import org.alfresco.service.cmr.workflow.WorkflowTask; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Helper class for common Workflow functionality. - *

- * This class should be replaced with calls to a WorkflowService once it is available. - * - * @author Kevin Roast - */ -public class WorkflowUtil -{ - private static Log logger = LogFactory.getLog(WorkflowUtil.class); - - /** - * Execute the Approve step for the Simple Workflow on a node. - * - * @param ref NodeRef to the node with the workflow - * @param nodeService NodeService instance - * @param copyService CopyService instance - * - * @throws AlfrescoRuntimeException - */ - public static void approve(final NodeRef ref, final NodeService nodeService, final CopyService copyService) - throws AlfrescoRuntimeException - { - Node docNode = new Node(ref); - - if (docNode.hasAspect(ApplicationModel.ASPECT_SIMPLE_WORKFLOW) == false) - { - throw new AlfrescoRuntimeException("Cannot approve a node that is not part of a workflow."); - } - - // get the simple workflow aspect properties - Map props = docNode.getProperties(); - - Boolean approveMove = (Boolean)props.get(ApplicationModel.PROP_APPROVE_MOVE.toString()); - NodeRef approveFolder = (NodeRef)props.get(ApplicationModel.PROP_APPROVE_FOLDER.toString()); - - if (approveMove.booleanValue()) - { - // first we need to take off the simpleworkflow aspect - nodeService.removeAspect(ref, ApplicationModel.ASPECT_SIMPLE_WORKFLOW); - - // move the node to the specified folder - String qname = QName.createValidLocalName(docNode.getName()); - nodeService.moveNode(ref, approveFolder, ContentModel.ASSOC_CONTAINS, - QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, qname)); - } - else - { - // first we need to take off the simpleworkflow aspect - // NOTE: run as system to allow Consumers to copy an item - AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork() - { - public String doWork() throws Exception - { - nodeService.removeAspect(ref, ApplicationModel.ASPECT_SIMPLE_WORKFLOW); - return null; - } - }, AuthenticationUtil.getSystemUserName()); - - // copy the node to the specified folder - String name = docNode.getName(); - String qname = QName.createValidLocalName(name); - NodeRef newNode = copyService.copy(ref, approveFolder, ContentModel.ASSOC_CONTAINS, - QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, qname), true); - - // the copy service does not copy the name of the node so we - // need to update the property on the copied item - nodeService.setProperty(newNode, ContentModel.PROP_NAME, name); - } - - if (logger.isDebugEnabled()) - { - String movedCopied = approveMove ? "moved" : "copied"; - logger.debug("Node has been approved and " + movedCopied + " to folder with id of " + - approveFolder.getId()); - } - } - - /** - * Execute the Reject step for the Simple Workflow on a node. - * - * @param ref NodeRef to the node with the workflow - * @param nodeService NodeService instance - * @param copyService CopyService instance - * - * @throws AlfrescoRuntimeException - */ - public static void reject(NodeRef ref, NodeService nodeService, CopyService copyService) - throws AlfrescoRuntimeException - { - Node docNode = new Node(ref); - - if (docNode.hasAspect(ApplicationModel.ASPECT_SIMPLE_WORKFLOW) == false) - { - throw new AlfrescoRuntimeException("Cannot reject a node that is not part of a workflow."); - } - - // get the simple workflow aspect properties - Map props = docNode.getProperties(); - - String rejectStep = (String)props.get(ApplicationModel.PROP_REJECT_STEP.toString()); - Boolean rejectMove = (Boolean)props.get(ApplicationModel.PROP_REJECT_MOVE.toString()); - NodeRef rejectFolder = (NodeRef)props.get(ApplicationModel.PROP_REJECT_FOLDER.toString()); - - if (rejectStep == null && rejectMove == null && rejectFolder == null) - { - throw new AlfrescoRuntimeException("The workflow does not have a reject step defined."); - } - - // first we need to take off the simpleworkflow aspect - nodeService.removeAspect(ref, ApplicationModel.ASPECT_SIMPLE_WORKFLOW); - - if (rejectMove != null && rejectMove.booleanValue()) - { - // move the document to the specified folder - String qname = QName.createValidLocalName(docNode.getName()); - nodeService.moveNode(ref, rejectFolder, ContentModel.ASSOC_CONTAINS, - QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, qname)); - } - else - { - // copy the document to the specified folder - String name = docNode.getName(); - String qname = QName.createValidLocalName(name); - NodeRef newNode = copyService.copy(ref, rejectFolder, ContentModel.ASSOC_CONTAINS, - QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, qname), true); - - // the copy service does not copy the name of the node so we - // need to update the property on the copied item - nodeService.setProperty(newNode, ContentModel.PROP_NAME, name); - } - - if (logger.isDebugEnabled()) - { - String movedCopied = rejectMove ? "moved" : "copied"; - logger.debug("Node has been rejected and " + movedCopied + " to folder with id of " + - rejectFolder.getId()); - } - } - - /** - * Prepares the given node for persistence in the workflow engine. - * - * @param node The node to package up for persistence - * @return The map of data representing the node - */ - @SuppressWarnings("unchecked") - public static Map prepareTaskParams(Node node) - { - Map params = new HashMap(); - - // marshal the properties and associations captured by the property sheet - // back into a Map to pass to the workflow service - - // go through all the properties in the transient node and add them to params map - Map props = node.getProperties(); - for (String propName : props.keySet()) - { - QName propQName = Repository.resolveToQName(propName); - params.put(propQName, (Serializable)props.get(propName)); - } - - // go through any associations that have been added to the start task - // and build a list of NodeRefs representing the targets - Map> assocs = node.getAddedAssociations(); - for (String assocName : assocs.keySet()) - { - QName assocQName = Repository.resolveToQName(assocName); - - // get the associations added and create list of targets - Map addedAssocs = assocs.get(assocName); - List originalAssocRefs = (List) node.getAssociations().get(assocName); - List targets = new ArrayList(addedAssocs.size()); - - if (originalAssocRefs != null) - { - for (AssociationRef assoc : originalAssocRefs) - { - targets.add(assoc.getTargetRef()); - } - } - - for (AssociationRef assoc : addedAssocs.values()) - { - targets.add(assoc.getTargetRef()); - } - - params.put(assocQName, (Serializable)targets); - } - - // go through the removed associations and either setup or adjust the - // parameters map accordingly - assocs = node.getRemovedAssociations(); - - for (String assocName : assocs.keySet()) - { - QName assocQName = Repository.resolveToQName(assocName); - - // get the associations removed and create list of targets - Map removedAssocs = assocs.get(assocName); - List targets = (List)params.get(assocQName); - - if (targets == null) - { - // if there weren't any assocs of this type added get the current - // set of assocs from the node - List originalAssocRefs = (List)node.getAssociations().get(assocName); - targets = new ArrayList(originalAssocRefs.size()); - - for (AssociationRef assoc : originalAssocRefs) - { - targets.add(assoc.getTargetRef()); - } - } - - // remove the assocs the user deleted - for (AssociationRef assoc : removedAssocs.values()) - { - targets.remove(assoc.getTargetRef()); - } - - params.put(assocQName, (Serializable)targets); - } - - // TODO: Deal with child associations if and when we need to support - // them for workflow tasks, for now warn that they are being used - Map childAssocs = node.getAddedChildAssociations(); - if (childAssocs.size() > 0) - { - if (logger.isWarnEnabled()) - logger.warn("Child associations are present but are not supported for workflow tasks, ignoring..."); - } - - return params; - } - - public static boolean isTaskEditable(String taskId, ServletContext sc) - { - if(taskId ==null|| taskId.isEmpty()) - { - return false; - } - ServiceRegistry serviceRegistry = Repository.getServiceRegistry(sc); - String username = serviceRegistry.getAuthenticationService().getCurrentUserName(); - WorkflowService workflowService = serviceRegistry.getWorkflowService(); - WorkflowTask task = workflowService.getTaskById(taskId); - return workflowService.isTaskEditable(task, username); - } -} diff --git a/war/src/main/java/org/alfresco/web/config/ActionsConfigElement.java b/war/src/main/java/org/alfresco/web/config/ActionsConfigElement.java deleted file mode 100644 index 9f90244047..0000000000 --- a/war/src/main/java/org/alfresco/web/config/ActionsConfigElement.java +++ /dev/null @@ -1,344 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.element.ConfigElementAdapter; -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.web.action.ActionEvaluator; -import org.alfresco.web.bean.repository.Repository; - -/** - * Action config element. - * - * @author Kevin Roast - */ -public class ActionsConfigElement extends ConfigElementAdapter -{ - public static final String CONFIG_ELEMENT_ID = "actions"; - - private Map actionDefs = new HashMap(32, 1.0f); - private Map actionGroups = new HashMap(16, 1.0f); - - /** - * Default constructor - */ - public ActionsConfigElement() - { - super(CONFIG_ELEMENT_ID); - } - - /** - * @param name String - */ - public ActionsConfigElement(String name) - { - super(name); - } - - /** - * @see org.springframework.extensions.config.element.ConfigElementAdapter#getChildren() - */ - public List getChildren() - { - throw new ConfigException("Reading the Actions config via the generic interfaces is not supported"); - } - - /** - * @see org.springframework.extensions.config.element.ConfigElementAdapter#combine(org.springframework.extensions.config.ConfigElement) - */ - public ConfigElement combine(ConfigElement configElement) - { - ActionsConfigElement newElement = (ActionsConfigElement)configElement; - ActionsConfigElement combinedElement = new ActionsConfigElement(); - - // add the existing action definitions - combinedElement.actionDefs.putAll(this.actionDefs); - - // overwrite any existing action definitions i.e. don't combine - combinedElement.actionDefs.putAll(newElement.actionDefs); - - // add the existing action groups - Map combinedActionGroups = new HashMap(this.actionGroups.size()); - try - { - for (ActionGroup group : this.actionGroups.values()) - { - combinedActionGroups.put(group.getId(), (ActionGroup)group.clone()); - } - } - catch (CloneNotSupportedException e) - { - throw new AlfrescoRuntimeException("clone() required on ActionGroup class.", e); - } - combinedElement.actionGroups = combinedActionGroups; - - // any new action groups with the same name must be combined - for (ActionGroup newGroup : newElement.actionGroups.values()) - { - if (combinedElement.actionGroups.containsKey(newGroup.getId())) - { - // there is already a group with this id, combine it with the new one - ActionGroup combinedGroup = combinedElement.actionGroups.get(newGroup.getId()); - if (newGroup.ShowLink != combinedGroup.ShowLink) - { - combinedGroup.ShowLink = newGroup.ShowLink; - } - if (newGroup.Style != null) - { - combinedGroup.Style = newGroup.Style; - } - if (newGroup.StyleClass != null) - { - combinedGroup.StyleClass = newGroup.StyleClass; - } - - // add all the actions from the new group to the combined one - for (String actionRef : newGroup.getAllActions()) - { - combinedGroup.addAction(actionRef); - } - - // add all the hidden actions from the new group to the combined one - for (String actionRef : newGroup.getHiddenActions()) - { - combinedGroup.hideAction(actionRef); - } - } - else - { - // it's a new group so just add it - combinedElement.actionGroups.put(newGroup.getId(), newGroup); - } - } - - return combinedElement; - } - - /*package*/ void addActionDefinition(ActionDefinition actionDef) - { - actionDefs.put(actionDef.getId(), actionDef); - } - - public ActionDefinition getActionDefinition(String id) - { - return actionDefs.get(id); - } - - /*package*/ void addActionGroup(ActionGroup group) - { - actionGroups.put(group.getId(), group); - } - - public ActionGroup getActionGroup(String id) - { - return actionGroups.get(id); - } - - - /** - * Simple class representing the definition of a UI action. - * - * @author Kevin Roast - */ - public static class ActionDefinition - { - public ActionDefinition(String id) - { - if (id == null || id.length() == 0) - { - throw new IllegalArgumentException("ActionDefinition ID is mandatory."); - } - this.id = id; - } - - public String getId() - { - return id; - } - - public void addAllowPermission(String permission) - { - if (permissionAllow == null) - { - permissionAllow = new ArrayList(2); - } - permissionAllow.add(permission); - } - - public void addDenyPermission(String permission) - { - if (permissionDeny == null) - { - permissionDeny = new ArrayList(1); - } - permissionDeny.add(permission); - } - - public List getAllowPermissions() - { - return permissionAllow; - } - - public List getDenyPermissions() - { - return permissionDeny; - } - - public void addParam(String name, String value) - { - if (params == null) - { - params = new HashMap(1, 1.0f); - } - params.put(name, value); - } - - public Map getParams() - { - return params; - } - - String id; - private List permissionAllow = null; - private List permissionDeny = null; - private Map params = null; - - public ActionEvaluator Evaluator = null; - public String Label; - public String LabelMsg; - public String Tooltip; - public String TooltipMsg; - public boolean ShowLink = true; - public String Style; - public String StyleClass; - public String Image; - public String ActionListener; - public String Action; - public String Href; - public String Target; - public String Script; - public String Onclick; - } - - - /** - * Simple class representing a group of UI actions. - * - * @author Kevin Roast - */ - public static class ActionGroup implements Iterable, Cloneable - { - public ActionGroup(String id) - { - if (id == null || id.length() == 0) - { - throw new IllegalArgumentException("ActionGroup ID is mandatory."); - } - this.id = id; - } - - @Override - protected Object clone() throws CloneNotSupportedException - { - ActionGroup clone = new ActionGroup(id); - clone.actions = (Set)((LinkedHashSet)actions).clone(); - clone.hiddenActions = (Set)((HashSet)hiddenActions).clone(); - clone.ShowLink = ShowLink; - clone.Style = Style; - clone.StyleClass = StyleClass; - return clone; - } - - public String getId() - { - return id; - } - - /** - * @return Iterator over the visible ActionDefinition IDs referenced by this group - */ - public Iterator iterator() - { - // create a list of the visible actions and return it's iterator - ArrayList visibleActions = new ArrayList(this.actions.size()); - for (String actionId : this.actions) - { - if (this.hiddenActions.contains(actionId) == false) - { - visibleActions.add(actionId); - } - } - - visibleActions.trimToSize(); - - return visibleActions.iterator(); - } - - /*package*/ void addAction(String actionId) - { - actions.add(actionId); - } - - /*package*/ void hideAction(String actionId) - { - this.hiddenActions.add(actionId); - } - - /*package*/ Set getAllActions() - { - return this.actions; - } - - /*package*/ Set getHiddenActions() - { - return this.hiddenActions; - } - - private String id; - - /** the action definitions, we use a Linked HashSet to ensure we do not have more - than one action with the same Id and that the insertion order is preserved */ - private Set actions = new LinkedHashSet(16, 1.0f); - - /** the actions that have been hidden */ - private Set hiddenActions = new HashSet(4, 1.0f); - - public boolean ShowLink; - public String Style; - public String StyleClass; - } -} diff --git a/war/src/main/java/org/alfresco/web/config/ActionsElementReader.java b/war/src/main/java/org/alfresco/web/config/ActionsElementReader.java deleted file mode 100644 index e70728378e..0000000000 --- a/war/src/main/java/org/alfresco/web/config/ActionsElementReader.java +++ /dev/null @@ -1,279 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.util.Iterator; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.xml.elementreader.ConfigElementReader; -import org.alfresco.web.action.ActionEvaluator; -import org.alfresco.web.config.ActionsConfigElement.ActionDefinition; -import org.alfresco.web.config.ActionsConfigElement.ActionGroup; -import org.dom4j.Element; - -/** - * Config Element Reader for the "Action" config blocks. - * - * @author Kevin Roast - */ -public class ActionsElementReader implements ConfigElementReader -{ - public static final String ELEMENT_ACTION = "action"; - public static final String ELEMENT_ACTIONGROUP = "action-group"; - public static final String ELEMENT_PERMISSIONS = "permissions"; - public static final String ELEMENT_PERMISSION = "permission"; - public static final String ELEMENT_EVALUATOR = "evaluator"; - public static final String ELEMENT_LABEL = "label"; - public static final String ELEMENT_LABELMSG = "label-id"; - public static final String ELEMENT_TOOLTIP = "tooltip"; - public static final String ELEMENT_TOOLTIPMSG = "tooltip-id"; - public static final String ELEMENT_SHOWLINK = "show-link"; - public static final String ELEMENT_STYLE = "style"; - public static final String ELEMENT_STYLECLASS = "style-class"; - public static final String ELEMENT_IMAGE = "image"; - public static final String ELEMENT_ACTIONLISTENER = "action-listener"; - public static final String ELEMENT_ONCLICK = "onclick"; - public static final String ELEMENT_HREF = "href"; - public static final String ELEMENT_TARGET = "target"; - public static final String ELEMENT_SCRIPT = "script"; - public static final String ELEMENT_PARAMS = "params"; - public static final String ELEMENT_PARAM = "param"; - public static final String ATTRIBUTE_ID = "id"; - public static final String ATTRIBUTE_IDREF = "idref"; - public static final String ATTRIBUTE_NAME = "name"; - public static final String ATTRIBUTE_ALLOW = "allow"; - public static final String ATTRIBUTE_HIDE = "hide"; - - /** - * @see org.springframework.extensions.config.xml.elementreader.ConfigElementReader#parse(org.dom4j.Element) - */ - @SuppressWarnings("unchecked") - public ConfigElement parse(Element element) - { - ActionsConfigElement configElement = new ActionsConfigElement(); - - if (element != null) - { - if (ActionsConfigElement.CONFIG_ELEMENT_ID.equals(element.getName()) == false) - { - throw new ConfigException("ActionsElementReader can only parse config elements of type 'Actions'"); - } - - Iterator actionItr = element.elementIterator(ELEMENT_ACTION); - while (actionItr.hasNext()) - { - // work on each 'action' element in turn - Element actionElement = actionItr.next(); - - // parse the action definition for the element - ActionDefinition actionDef = parseActionDefinition(actionElement); - - // add our finished action def to the map of all actions - configElement.addActionDefinition(actionDef); - } - - Iterator actionGroupItr = element.elementIterator(ELEMENT_ACTIONGROUP); - while (actionGroupItr.hasNext()) - { - // work on each 'action-group' element in turn - Element groupElement = actionGroupItr.next(); - String groupId = groupElement.attributeValue(ATTRIBUTE_ID); - if (groupId == null || groupId.length() == 0) - { - throw new ConfigException("'action-group' config element specified without mandatory 'id' attribute."); - } - - // build a structure to represent the action group - ActionGroup actionGroup = new ActionGroup(groupId); - - // loop round each action ref and add them to the list for this action group - Iterator actionRefItr = groupElement.elementIterator(ELEMENT_ACTION); - while (actionRefItr.hasNext()) - { - Element actionRefElement = actionRefItr.next(); - - // look for an action referred to be Id - this is the common use-case - String idRef = actionRefElement.attributeValue(ATTRIBUTE_IDREF); - if (idRef == null || idRef.length() == 0) - { - // look for an action defined directly rather than referenced by Id - String id = actionRefElement.attributeValue(ATTRIBUTE_ID); - if (id != null && id.length() != 0) - { - ActionDefinition def = parseActionDefinition(actionRefElement); - // override action definition ID based on the group name to avoid conflicts - def.id = actionGroup.getId() + '_' + def.getId(); - configElement.addActionDefinition(def); - actionGroup.addAction(def.getId()); - } - } - else - { - // look for the hide attribute - String hide = actionRefElement.attributeValue(ATTRIBUTE_HIDE); - if (hide != null && Boolean.parseBoolean(hide)) - { - actionGroup.hideAction(idRef); - } - else - { - // add the action definition ID to the group - actionGroup.addAction(idRef); - } - } - } - - // get simple string properties for the action group - actionGroup.Style = groupElement.elementTextTrim(ELEMENT_STYLE); - actionGroup.StyleClass = groupElement.elementTextTrim(ELEMENT_STYLECLASS); - if (groupElement.element(ELEMENT_SHOWLINK) != null) - { - actionGroup.ShowLink = Boolean.parseBoolean(groupElement.element(ELEMENT_SHOWLINK).getTextTrim()); - } - - // add the action group to the map of all action groups - configElement.addActionGroup(actionGroup); - } - } - - return configElement; - } - - /** - * Parse an ActionDefinition from the specific config element. - * - * @param actionElement The config element containing the action def - * - * @return The populated ActionDefinition - */ - public ActionDefinition parseActionDefinition(Element actionElement) - { - String actionId = actionElement.attributeValue(ATTRIBUTE_ID); - if (actionId == null || actionId.length() == 0) - { - throw new ConfigException("'action' config element specified without mandatory 'id' attribute."); - } - - // build a structure to represent the action definition - ActionDefinition actionDef = new ActionDefinition(actionId); - - // look for the permissions element - it can contain many permission - Element permissionsElement = actionElement.element(ELEMENT_PERMISSIONS); - if (permissionsElement != null) - { - // read and process each permission element - Iterator permissionItr = permissionsElement.elementIterator(ELEMENT_PERMISSION); - while (permissionItr.hasNext()) - { - Element permissionElement = permissionItr.next(); - boolean allow = true; - if (permissionElement.attributeValue(ATTRIBUTE_ALLOW) != null) - { - allow = Boolean.parseBoolean(permissionElement.attributeValue(ATTRIBUTE_ALLOW)); - } - String permissionValue = permissionElement.getTextTrim(); - if (allow) - { - actionDef.addAllowPermission(permissionValue); - } - else - { - actionDef.addDenyPermission(permissionValue); - } - } - } - - // find and construct the specified evaluator class - Element evaluatorElement = actionElement.element(ELEMENT_EVALUATOR); - if (evaluatorElement != null) - { - Object evaluator; - String className = evaluatorElement.getTextTrim(); - try - { - Class clazz = Class.forName(className); - evaluator = clazz.newInstance(); - } - catch (Throwable err) - { - throw new ConfigException("Unable to construct action '" + - actionId + "' evaluator classname: " +className); - } - if (evaluator instanceof ActionEvaluator == false) - { - throw new ConfigException("Action '" + actionId + "' evaluator class '" + - className + "' does not implement ActionEvaluator interface."); - } - actionDef.Evaluator = (ActionEvaluator)evaluator; - } - - // find any parameter values that the action requires - Element paramsElement = actionElement.element(ELEMENT_PARAMS); - if (paramsElement != null) - { - Iterator paramsItr = paramsElement.elementIterator(ELEMENT_PARAM); - while (paramsItr.hasNext()) - { - Element paramElement = paramsItr.next(); - String name = paramElement.attributeValue(ATTRIBUTE_NAME); - if (name == null || name.length() == 0) - { - throw new ConfigException("Action '" + actionId + - "' param does not have mandatory 'name' attribute."); - } - String value = paramElement.getTextTrim(); - if (value == null || value.length() == 0) - { - throw new ConfigException("Action '" + actionId + "' param '" + name + "'" + - "' does not have a value."); - } - actionDef.addParam(name, value); - } - } - - // get simple string properties for the action - actionDef.Label = actionElement.elementTextTrim(ELEMENT_LABEL); - actionDef.LabelMsg = actionElement.elementTextTrim(ELEMENT_LABELMSG); - actionDef.Tooltip = actionElement.elementTextTrim(ELEMENT_TOOLTIP); - actionDef.TooltipMsg = actionElement.elementTextTrim(ELEMENT_TOOLTIPMSG); - actionDef.Href = actionElement.elementTextTrim(ELEMENT_HREF); - actionDef.Target = actionElement.elementTextTrim(ELEMENT_TARGET); - actionDef.Script = actionElement.elementTextTrim(ELEMENT_SCRIPT); - actionDef.Action = actionElement.elementTextTrim(ELEMENT_ACTION); - actionDef.ActionListener = actionElement.elementTextTrim(ELEMENT_ACTIONLISTENER); - actionDef.Onclick = actionElement.elementTextTrim(ELEMENT_ONCLICK); - actionDef.Image = actionElement.elementTextTrim(ELEMENT_IMAGE); - actionDef.Style = actionElement.elementTextTrim(ELEMENT_STYLE); - actionDef.StyleClass = actionElement.elementTextTrim(ELEMENT_STYLECLASS); - if (actionElement.element(ELEMENT_SHOWLINK) != null) - { - actionDef.ShowLink = Boolean.parseBoolean(actionElement.element(ELEMENT_SHOWLINK).getTextTrim()); - } - - return actionDef; - } -} diff --git a/war/src/main/java/org/alfresco/web/config/AdvancedSearchConfigElement.java b/war/src/main/java/org/alfresco/web/config/AdvancedSearchConfigElement.java deleted file mode 100644 index 3a7a5f6446..0000000000 --- a/war/src/main/java/org/alfresco/web/config/AdvancedSearchConfigElement.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.element.ConfigElementAdapter; - -/** - * Custom config element that represents config values for advanced search - * - * @author Gavin Cornwell - */ -public class AdvancedSearchConfigElement extends ConfigElementAdapter implements Serializable -{ - private static final long serialVersionUID = -6427054671579839728L; - - public static final String CONFIG_ELEMENT_ID = "advanced-search"; - - private List contentTypes = null; - private List folderTypes = null; - private List customProps = null; - - /** - * Default Constructor - */ - public AdvancedSearchConfigElement() - { - super(CONFIG_ELEMENT_ID); - } - - /** - * Constructor - * - * @param name Name of the element this config element represents - */ - public AdvancedSearchConfigElement(String name) - { - super(name); - } - - /** - * @see org.springframework.extensions.config.element.ConfigElementAdapter#getChildren() - */ - @Override - public List getChildren() - { - throw new ConfigException("Reading the advanced search config via the generic interfaces is not supported"); - } - - /** - * @see org.springframework.extensions.config.element.ConfigElementAdapter#combine(org.springframework.extensions.config.ConfigElement) - */ - public ConfigElement combine(ConfigElement configElement) - { - AdvancedSearchConfigElement newElement = (AdvancedSearchConfigElement)configElement; - AdvancedSearchConfigElement combinedElement = new AdvancedSearchConfigElement(); - - // just copy the list of types and properties from this instance to the new one - if (this.contentTypes != null) - { - for (String type : this.contentTypes) - { - combinedElement.addContentType(type); - } - } - if (this.folderTypes != null) - { - for (String type : this.folderTypes) - { - combinedElement.addFolderType(type); - } - } - - if (this.customProps != null) - { - for (CustomProperty property : this.customProps) - { - combinedElement.addCustomProperty(property); - } - } - - // now add those types and custom properties from the element to be combined - if (newElement.getContentTypes() != null) - { - for (String type : newElement.getContentTypes()) - { - combinedElement.addContentType(type); - } - } - - if (newElement.getFolderTypes() != null) - { - for (String type : newElement.getFolderTypes()) - { - combinedElement.addFolderType(type); - } - } - - if (newElement.getCustomProperties() != null) - { - for (CustomProperty property : newElement.getCustomProperties()) - { - combinedElement.addCustomProperty(property); - } - } - - return combinedElement; - } - - /** - * @return Returns the contentTypes. - */ - public List getContentTypes() - { - return this.contentTypes; - } - - /** - * @param contentTypes The contentTypes to set. - */ - /*package*/ void setContentTypes(List contentTypes) - { - this.contentTypes = contentTypes; - } - - /** - * @param contentType Adds the given content type to the list - */ - /*package*/ void addContentType(String contentType) - { - if (this.contentTypes == null) - { - this.contentTypes = new ArrayList(3); - } - - if (this.contentTypes.contains(contentType) == false) - { - this.contentTypes.add(contentType); - } - } - - /** - * @return Returns the folderTypes. - */ - public List getFolderTypes() - { - return this.folderTypes; - } - - /** - * @param folderTypes The folderTypes to set. - */ - /*package*/ void setFolderTypes(List folderTypes) - { - this.folderTypes = folderTypes; - } - - /** - * @param folderType Adds the given folder type to the list - */ - /*package*/ void addFolderType(String folderType) - { - if (this.folderTypes == null) - { - this.folderTypes = new ArrayList(3); - } - - if (this.folderTypes.contains(folderType) == false) - { - this.folderTypes.add(folderType); - } - } - - /** - * @return Returns the customProps. - */ - public List getCustomProperties() - { - return this.customProps; - } - - /** - * @param customProps The customProps to set. - */ - /*package*/ void setCustomProperties(List customProps) - { - this.customProps = customProps; - } - - /** - * @param property Adds the given custom property to the list - */ - /*package*/ void addCustomProperty(CustomProperty property) - { - if (this.customProps == null) - { - this.customProps = new ArrayList(3); - } - - // TODO: Determine if the CustomProperty being added is already - // in the list - - this.customProps.add(property); - } - - /** - * Simple wrapper class for custom advanced search property - * @author Kevin Roast - */ - public static class CustomProperty implements Serializable - { - private static final long serialVersionUID = 1457092137913897740L; - - CustomProperty(String type, String aspect, String property, String labelId) - { - Type = type; - Aspect = aspect; - Property = property; - LabelId = labelId; - } - - public String Type; - public String Aspect; - public String Property; - public String LabelId; - } -} diff --git a/war/src/main/java/org/alfresco/web/config/AdvancedSearchElementReader.java b/war/src/main/java/org/alfresco/web/config/AdvancedSearchElementReader.java deleted file mode 100644 index 57961dd7b8..0000000000 --- a/war/src/main/java/org/alfresco/web/config/AdvancedSearchElementReader.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.xml.elementreader.ConfigElementReader; -import org.alfresco.web.config.AdvancedSearchConfigElement.CustomProperty; -import org.dom4j.Element; - -/** - * Custom element reader to parse config for advanced search - * - * @author Gavin Cornwell - */ -public class AdvancedSearchElementReader implements ConfigElementReader -{ - public static final String ELEMENT_CONTENTTYPES = "content-types"; - public static final String ELEMENT_FOLDERTYPES = "folder-types"; - public static final String ELEMENT_TYPE = "type"; - public static final String ELEMENT_CUSTOMPROPS = "custom-properties"; - public static final String ELEMENT_METADATA = "meta-data"; - public static final String ATTRIBUTE_NAME = "name"; - public static final String ATTRIBUTE_TYPE = "type"; - public static final String ATTRIBUTE_PROPERTY = "property"; - public static final String ATTRIBUTE_ASPECT = "aspect"; - public static final String ATTRIBUTE_DISPLAYLABEL = "display-label-id"; - - /** - * @see org.springframework.extensions.config.xml.elementreader.ConfigElementReader#parse(org.dom4j.Element) - */ - @SuppressWarnings("unchecked") - public ConfigElement parse(Element element) - { - AdvancedSearchConfigElement configElement = null; - - if (element != null) - { - String name = element.getName(); - if (name.equals(AdvancedSearchConfigElement.CONFIG_ELEMENT_ID) == false) - { - throw new ConfigException("AdvancedSearchElementReader can only parse " + - AdvancedSearchConfigElement.CONFIG_ELEMENT_ID + " elements, the element passed was '" + - name + "'"); - } - - configElement = new AdvancedSearchConfigElement(); - - // get the list of content types - Element contentTypes = element.element(ELEMENT_CONTENTTYPES); - if (contentTypes != null) - { - Iterator typesItr = contentTypes.elementIterator(ELEMENT_TYPE); - List types = new ArrayList(5); - while (typesItr.hasNext()) - { - Element contentType = typesItr.next(); - String type = contentType.attributeValue(ATTRIBUTE_NAME); - if (type != null) - { - types.add(type); - } - } - configElement.setContentTypes(types); - } - - // get the list of folder types - Element folderTypes = element.element(ELEMENT_FOLDERTYPES); - if (folderTypes != null) - { - Iterator typesItr = folderTypes.elementIterator(ELEMENT_TYPE); - List types = new ArrayList(5); - while (typesItr.hasNext()) - { - Element folderType = typesItr.next(); - String type = folderType.attributeValue(ATTRIBUTE_NAME); - if (type != null) - { - types.add(type); - } - } - configElement.setFolderTypes(types); - } - - // get the list of custom properties to display - Element customProps = element.element(ELEMENT_CUSTOMPROPS); - if (customProps != null) - { - Iterator propsItr = customProps.elementIterator(ELEMENT_METADATA); - List props = new ArrayList(5); - while (propsItr.hasNext()) - { - Element propElement = propsItr.next(); - String type = propElement.attributeValue(ATTRIBUTE_TYPE); - String aspect = propElement.attributeValue(ATTRIBUTE_ASPECT); - String prop = propElement.attributeValue(ATTRIBUTE_PROPERTY); - String labelId = propElement.attributeValue(ATTRIBUTE_DISPLAYLABEL); - props.add(new AdvancedSearchConfigElement.CustomProperty(type, aspect, prop, labelId)); - } - configElement.setCustomProperties(props); - } - } - - return configElement; - } -} diff --git a/war/src/main/java/org/alfresco/web/config/AspectEvaluator.java b/war/src/main/java/org/alfresco/web/config/AspectEvaluator.java deleted file mode 100644 index 8ce93e7ce9..0000000000 --- a/war/src/main/java/org/alfresco/web/config/AspectEvaluator.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.util.Set; - -import org.springframework.extensions.config.evaluator.Evaluator; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; - -/** - * Evaluator that determines whether a given object has a particular aspect applied - * - * @author gavinc - */ -public final class AspectEvaluator implements Evaluator -{ - /** - * Determines whether the given aspect is applied to the given object - * - * @see org.springframework.extensions.config.evaluator.Evaluator#applies(java.lang.Object, java.lang.String) - */ - public boolean applies(Object obj, String condition) - { - boolean result = false; - - if (obj instanceof Node) - { - Set aspects = ((Node)obj).getAspects(); - if (aspects != null) - { - QName spaceQName = Repository.resolveToQName(condition); - result = aspects.contains(spaceQName); - } - } - - return result; - } -} diff --git a/war/src/main/java/org/alfresco/web/config/ClientConfigElement.java b/war/src/main/java/org/alfresco/web/config/ClientConfigElement.java deleted file mode 100644 index 164d25ce8d..0000000000 --- a/war/src/main/java/org/alfresco/web/config/ClientConfigElement.java +++ /dev/null @@ -1,942 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.util.ArrayList; -import java.util.List; - -import org.alfresco.service.namespace.QName; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.element.ConfigElementAdapter; - -/** - * Custom config element that represents config values for the client - * - * @author Kevin Roast - */ -public class ClientConfigElement extends ConfigElementAdapter -{ - private static final long serialVersionUID = 825650925215057110L; - - private static Log logger = LogFactory.getLog(ClientConfigElement.class); - - public static final String CONFIG_ELEMENT_ID = "client"; - public static final String BREADCRUMB_PATH = "path"; - public static final String BREADCRUMB_LOCATION = "location"; - - private static final String DEFAULT_FROM_ADDRESS = "alfresco@alfresco.org"; - - private String fromEmailAddress = DEFAULT_FROM_ADDRESS; - private String errorPage = null; - private String loginPage = null; - private int recentSpacesItems = 6; - private boolean shelfVisible = true; - private int searchMinimum = 3; - private boolean forceAndTerms = false; - private int searchMaxResults = -1; - private int selectorsSearchMaxResults = 500; - private int inviteUsersMaxResults = 500; - private int tasksCompletedMaxResults = 100; - private String helpUrl = null; - private String editLinkType = "http"; - private String homeSpacePermission = null; - private boolean nodeSummaryEnabled = true; - private String initialLocation = "myalfresco"; - private String defaultHomeSpacePath = "/app:company_home/app:user_homes"; - private boolean clipboardStatusVisible = true; - private boolean pasteAllAndClear = true; - private boolean allowGuestConfig = false; - private List simpleSearchAdditionalAttributes = null; - private int minUsernameLength = 2; - private int minPasswordLength = 3; - private int maxPasswordLength = 255; - private int minGroupNameLength = 3; - private String breadcrumbMode = BREADCRUMB_PATH; - private String cifsURLSuffix = null; - private boolean languageSelect = true; - private boolean zeroByteFileUploads = true; - private boolean userGroupAdmin = true; - private boolean allowUserConfig = true; - private int pickerSearchMinimum = 2; - private boolean checkContextAgainstPath = false; - private boolean allowUserScriptExecute = false; - private boolean isBulkFetchEnabled = true; - private String emailRegExp = "^([-A-Za-z0-9\\xc0-\\xff!#$%&'*+\\/=?^_`{}~|]+\\.)*[-A-Za-z0-9\\xc0-\\xff!#$%&'*+\\/=?^_`{}|~_]+@([\\.A-Za-z0-9_-])*[A-Za-z0-9_-]$"; - - /** - * Default Constructor - */ - public ClientConfigElement() - { - super(CONFIG_ELEMENT_ID); - } - - /** - * Constructor - * - * @param name Name of the element this config element represents - */ - public ClientConfigElement(String name) - { - super(name); - } - - /** - * @see org.springframework.extensions.config.element.ConfigElementAdapter#combine(org.springframework.extensions.config.ConfigElement) - */ - public ConfigElement combine(ConfigElement configElement) - { - ClientConfigElement newElement = (ClientConfigElement)configElement; - ClientConfigElement combinedElement = new ClientConfigElement(); - - // set those values that have changed - if (newElement.getEditLinkType() == null) - { - combinedElement.setEditLinkType(this.editLinkType); - } - else - { - combinedElement.setEditLinkType(newElement.getEditLinkType()); - } - - if (newElement.getErrorPage() == null) - { - combinedElement.setErrorPage(this.errorPage); - } - else - { - combinedElement.setErrorPage(newElement.getErrorPage()); - } - - if (newElement.getLoginPage() == null) - { - combinedElement.setLoginPage(this.loginPage); - } - else - { - combinedElement.setLoginPage(newElement.getLoginPage()); - } - - if (newElement.getHelpUrl() == null ) - { - combinedElement.setHelpUrl(this.helpUrl); - } - else - { - combinedElement.setHelpUrl(newElement.getHelpUrl()); - } - - if (newElement.getHomeSpacePermission() == null) - { - combinedElement.setHomeSpacePermission(this.homeSpacePermission); - } - else - { - combinedElement.setHomeSpacePermission(newElement.getHomeSpacePermission()); - } - - if (newElement.getCifsURLSuffix() == null) - { - combinedElement.setCifsURLSuffix(this.cifsURLSuffix); - } - else - { - combinedElement.setCifsURLSuffix(newElement.getCifsURLSuffix()); - } - - if (newElement.getSimpleSearchAdditionalAttributes() == null) - { - combinedElement.setSimpleSearchAdditionalAttributes(this.simpleSearchAdditionalAttributes); - } - else - { - if (this.simpleSearchAdditionalAttributes == null) - { - // there aren't any existing attributes so just use the new set - combinedElement.setSimpleSearchAdditionalAttributes(newElement.getSimpleSearchAdditionalAttributes()); - } - else - { - // get the current list and add the additional attributes to it - List newAttrs = newElement.getSimpleSearchAdditionalAttributes(); - List combinedAttrs = new ArrayList( - this.simpleSearchAdditionalAttributes.size() + newAttrs.size()); - combinedAttrs.addAll(this.simpleSearchAdditionalAttributes); - combinedAttrs.addAll(newAttrs); - combinedElement.setSimpleSearchAdditionalAttributes(combinedAttrs); - } - } - - // override default values if they have changed - if (newElement.getDefaultHomeSpacePath() != null && - newElement.getDefaultHomeSpacePath().equals(combinedElement.getDefaultHomeSpacePath()) == false) - { - combinedElement.setDefaultHomeSpacePath(newElement.getDefaultHomeSpacePath()); - } - - if (newElement.getRecentSpacesItems() != combinedElement.getRecentSpacesItems()) - { - combinedElement.setRecentSpacesItems(newElement.getRecentSpacesItems()); - } - - if (newElement.getSearchMinimum() != combinedElement.getSearchMinimum()) - { - combinedElement.setSearchMinimum(newElement.getSearchMinimum()); - } - - if (newElement.getForceAndTerms() != combinedElement.getForceAndTerms()) - { - combinedElement.setForceAndTerms(newElement.getForceAndTerms()); - } - - if (newElement.getSearchMaxResults() != combinedElement.getSearchMaxResults()) - { - combinedElement.setSearchMaxResults(newElement.getSearchMaxResults()); - } - - if (newElement.getSelectorsSearchMaxResults() != combinedElement.getSelectorsSearchMaxResults()) - { - combinedElement.setSelectorsSearchMaxResults(newElement.getSelectorsSearchMaxResults()); - } - - if (newElement.getInviteUsersMaxResults() != combinedElement.getInviteUsersMaxResults()) - { - combinedElement.setInviteUsersMaxResults(newElement.getInviteUsersMaxResults()); - } - - if (newElement.getTasksCompletedMaxResults() != combinedElement.getTasksCompletedMaxResults()) - { - combinedElement.setTasksCompletedMaxResults(newElement.getTasksCompletedMaxResults()); - } - - if (newElement.isShelfVisible() != combinedElement.isShelfVisible()) - { - combinedElement.setShelfVisible(newElement.isShelfVisible()); - } - - if (newElement.isClipboardStatusVisible() != combinedElement.isClipboardStatusVisible()) - { - combinedElement.setClipboardStatusVisible(newElement.isClipboardStatusVisible()); - } - - if (newElement.isPasteAllAndClearEnabled() != combinedElement.isPasteAllAndClearEnabled()) - { - combinedElement.setPasteAllAndClearEnabled(newElement.isPasteAllAndClearEnabled()); - } - - if (newElement.getFromEmailAddress() != null && - (newElement.getFromEmailAddress().equals(combinedElement.getFromEmailAddress()) == false)) - { - combinedElement.setFromEmailAddress(newElement.getFromEmailAddress()); - } - - if (newElement.isNodeSummaryEnabled() != combinedElement.isNodeSummaryEnabled()) - { - combinedElement.setNodeSummaryEnabled(newElement.isNodeSummaryEnabled()); - } - - if (newElement.getInitialLocation() != null && - newElement.getInitialLocation().equals(combinedElement.getInitialLocation()) == false) - { - combinedElement.setInitialLocation(newElement.getInitialLocation()); - } - - if (newElement.getAllowGuestConfig() != combinedElement.getAllowGuestConfig()) - { - combinedElement.setAllowGuestConfig(newElement.getAllowGuestConfig()); - } - - if (newElement.getMinUsernameLength() != combinedElement.getMinUsernameLength()) - { - combinedElement.setMinUsernameLength(newElement.getMinUsernameLength()); - } - - if (newElement.getMinPasswordLength() != combinedElement.getMinPasswordLength()) - { - combinedElement.setMinPasswordLength(newElement.getMinPasswordLength()); - } - - if (newElement.getMaxPasswordLength() != combinedElement.getMaxPasswordLength()) - { - combinedElement.setMaxPasswordLength(newElement.getMaxPasswordLength()); - } - - if (newElement.getMinGroupNameLength() != combinedElement.getMinGroupNameLength()) - { - combinedElement.setMinGroupNameLength(newElement.getMinGroupNameLength()); - } - - if (newElement.getBreadcrumbMode() != null && - newElement.getBreadcrumbMode().equals(combinedElement.getBreadcrumbMode()) == false) - { - combinedElement.setBreadcrumbMode(newElement.getBreadcrumbMode()); - } - - if (newElement.isLanguageSelect() != combinedElement.isLanguageSelect()) - { - combinedElement.setLanguageSelect(newElement.isLanguageSelect()); - } - - if (newElement.isZeroByteFileUploads() != combinedElement.isZeroByteFileUploads()) - { - combinedElement.setZeroByteFileUploads(newElement.isZeroByteFileUploads()); - } - - if (newElement.getAllowUserConfig() != combinedElement.getAllowUserConfig()) - { - combinedElement.setAllowUserConfig(newElement.getAllowUserConfig()); - } - - if (newElement.isUserGroupAdmin() != combinedElement.isUserGroupAdmin()) - { - combinedElement.setUserGroupAdmin(newElement.isUserGroupAdmin()); - } - - if (newElement.getPickerSearchMinimum() != combinedElement.getPickerSearchMinimum()) - { - combinedElement.setPickerSearchMinimum(newElement.getPickerSearchMinimum()); - } - - if (newElement.getCheckContextAgainstPath() != combinedElement.getCheckContextAgainstPath()) - { - combinedElement.setCheckContextAgainstPath(newElement.getCheckContextAgainstPath()); - } - - if (newElement.getAllowUserScriptExecute() != combinedElement.getAllowUserScriptExecute()) - { - combinedElement.setAllowUserScriptExecute(newElement.getAllowUserScriptExecute()); - } - - return combinedElement; - } - - /** - * @return Returns the recentSpacesItems. - */ - public int getRecentSpacesItems() - { - return this.recentSpacesItems; - } - - /** - * @param recentSpacesItems The recentSpacesItems to set. - */ - /*package*/ void setRecentSpacesItems(int recentSpacesItems) - { - this.recentSpacesItems = recentSpacesItems; - } - - /** - * @return Returns if the shelf component is visible by default. - */ - public boolean isShelfVisible() - { - return this.shelfVisible; - } - - /** - * @param shelfVisible True if the shelf component is visible by default. - */ - /*package*/ void setShelfVisible(boolean shelfVisible) - { - this.shelfVisible = shelfVisible; - } - - /** - * @return Returns if the clipboard status messages are visible by default. - */ - public boolean isClipboardStatusVisible() - { - return this.clipboardStatusVisible; - } - - /** - * @param clipboardStatusVisible True if the clipboard status messages should be visible. - */ - /*package*/ void setClipboardStatusVisible(boolean clipboardStatusVisible) - { - this.clipboardStatusVisible = clipboardStatusVisible; - } - - /** - * @return Returns if the clipboard paste all action should clear the clipboard. - */ - public boolean isPasteAllAndClearEnabled() - { - return this.pasteAllAndClear; - } - - /** - * @param pasteAllAndClear Sets whether the paste all action should clear all items - * from the clipboard. - */ - /*package*/ void setPasteAllAndClearEnabled(boolean pasteAllAndClear) - { - this.pasteAllAndClear = pasteAllAndClear; - } - - /** - * @return The error page the application should use - */ - public String getErrorPage() - { - return this.errorPage; - } - - /** - * @param errorPage Sets the error page - */ - /*package*/ void setErrorPage(String errorPage) - { - this.errorPage = errorPage; - } - - /** - * @return Returns the login Page. - */ - public String getLoginPage() - { - return this.loginPage; - } - - /** - * @param loginPage The login Page to set. - */ - /*package*/ void setLoginPage(String loginPage) - { - this.loginPage = loginPage; - } - - /** - * @return Returns the help Url. - */ - public String getHelpUrl() - { - return this.helpUrl; - } - - /** - * @param helpUrl The help Url to set. - */ - /*package*/ void setHelpUrl(String helpUrl) - { - this.helpUrl = helpUrl; - } - - /** - * @return Returns the from email address, if one has not been set - * alfresco@alfresco.org will be returned - */ - public String getFromEmailAddress() - { - return this.fromEmailAddress; - } - - /** - * @param fromEmailAddress The from email address to set - */ - /*package*/ void setFromEmailAddress(String fromEmailAddress) - { - this.fromEmailAddress = fromEmailAddress; - } - - /** - * @return Returns the edit link type. - */ - public String getEditLinkType() - { - return this.editLinkType; - } - - /** - * @param editLinkType The edit link type to set. - */ - /*package*/ void setEditLinkType(String editLinkType) - { - this.editLinkType = editLinkType; - } - - /** - * @return Returns the search minimum number of characters. - */ - public int getSearchMinimum() - { - return this.searchMinimum; - } - - /** - * @param searchMinimum The searchMinimum to set. - */ - /*package*/ void setSearchMinimum(int searchMinimum) - { - this.searchMinimum = searchMinimum; - } - - /** - * @return If true enables AND text terms for simple/advanced search by default. - */ - public boolean getForceAndTerms() - { - return this.forceAndTerms; - } - - /** - * @param forceAndTerms True to enable AND text terms for simple/advanced search by default. - */ - /*package*/ void setForceAndTerms(boolean forceAndTerms) - { - this.forceAndTerms = forceAndTerms; - } - - /** - * If positive, this will limit the size of the result set from the search. - * - * @return The maximum number of results to show - */ - public int getSearchMaxResults() - { - return this.searchMaxResults; - } - - /** - * Set if the the result set from a search will be of limited size. - * If negative it is unlimited, by convention, this is set to -1. - * - * @param searchMaxResults int - */ - /*package*/ void setSearchMaxResults(int searchMaxResults) - { - this.searchMaxResults = searchMaxResults; - } - - /** - * If positive, this will limit the size of the result set from the search - * used in selector components. - * - * @return The maximum number of results to display - */ - public int getSelectorsSearchMaxResults() - { - return this.selectorsSearchMaxResults; - } - - /** - * Set if the the result set from a search for the selector components - * will be of limited size. If negative it is unlimited, by default, - * this is set to 500. - * - * @param selectorsSearchMaxResults int - */ - /*package*/ void setSelectorsSearchMaxResults(int selectorsSearchMaxResults) - { - this.selectorsSearchMaxResults = selectorsSearchMaxResults; - } - - /** - * If positive, this will limit the size of the result set from the - * invite users wizard. - * - * @return The maximum number of results to display - */ - public int getInviteUsersMaxResults() - { - return this.inviteUsersMaxResults; - } - - /** - * Set if the the result set from a search for the invite users wizard - * will be of limited size. If negative it is unlimited, by default, - * this is set to 500. - * - * @param inviteUsersMaxResults int - */ - /*package*/ void setInviteUsersMaxResults(int inviteUsersMaxResults) - { - this.inviteUsersMaxResults = inviteUsersMaxResults; - } - - /** - * If positive, this will limit the size of the result set of the - * completed tasks. - * - * @return The maximum number of completed tasks to display - */ - public int getTasksCompletedMaxResults() - { - return tasksCompletedMaxResults; - } - - /** - * Set if the the number of completed tasks displayed shall be limited. - * If negative it is unlimited, by default, this is set to 100. - * - * @param tasksCompletedMaxResults int - */ - /*package*/ void setTasksCompletedMaxResults(int tasksCompletedMaxResults) - { - this.tasksCompletedMaxResults = tasksCompletedMaxResults; - } - - /** - * @return Returns the default Home Space permissions. - */ - public String getHomeSpacePermission() - { - return this.homeSpacePermission; - } - - /** - * @param homeSpacePermission The default Home Space permission to set. - */ - /*package*/ void setHomeSpacePermission(String homeSpacePermission) - { - this.homeSpacePermission = homeSpacePermission; - } - - /** - * @return Returns the default Home Space path. - */ - public String getDefaultHomeSpacePath() - { - return this.defaultHomeSpacePath; - } - - /** - * @param defaultHomeSpacePath The default Home Space path to set. - */ - /*package*/ void setDefaultHomeSpacePath(String defaultHomeSpacePath) - { - this.defaultHomeSpacePath = defaultHomeSpacePath; - } - - /** - * @return Returns whether AJAX support is enabled in the client - */ - public boolean isNodeSummaryEnabled() - { - return this.nodeSummaryEnabled; - } - - /** - * Sets whether AJAX support is enabled in the client - * - * @param ajaxEnabled boolean - */ - /*package*/ void setNodeSummaryEnabled(boolean ajaxEnabled) - { - this.nodeSummaryEnabled = ajaxEnabled; - } - - /** - * @return Returns the default initial location for the user. - */ - public String getInitialLocation() - { - return this.initialLocation; - } - - /** - * @param initialLocation The initial location to set. - */ - /*package*/ void setInitialLocation(String initialLocation) - { - this.initialLocation = initialLocation; - } - - /*package*/ void setAllowGuestConfig(boolean allow) - { - this.allowGuestConfig = allow; - } - - public boolean getAllowGuestConfig() - { - return this.allowGuestConfig; - } - - /** - * @return Returns the additional attributes to search on a simple search - */ - public List getSimpleSearchAdditionalAttributes() - { - return this.simpleSearchAdditionalAttributes; - } - - /** - * @param simpleSearchAdditionalAttributes The additional simple search attributes - */ - /*package*/ void setSimpleSearchAdditionalAttributes(List simpleSearchAdditionalAttributes) - { - this.simpleSearchAdditionalAttributes = simpleSearchAdditionalAttributes; - } - - /** - * @return Returns the minimum length for a username. - */ - public int getMinUsernameLength() - { - return this.minUsernameLength; - } - - /** - * @param minUsernameLength The minimum length of a username - */ - /*package*/ void setMinUsernameLength(int minUsernameLength) - { - this.minUsernameLength = minUsernameLength; - } - - /** - * @return Returns the minimum length for a password. - */ - public int getMinPasswordLength() - { - return this.minPasswordLength; - } - - /** - * @param minPasswordLength The minimum length of a password - */ - /*package*/ void setMinPasswordLength(int minPasswordLength) - { - this.minPasswordLength = minPasswordLength; - } - - /** - * @return Returns the maximum length for a password. - */ - public int getMaxPasswordLength() - { - return this.maxPasswordLength; - } - - /** - * @param maxPasswordLength The maximum length of a password - */ - public void setMaxPasswordLength(int maxPasswordLength) - { - this.maxPasswordLength = maxPasswordLength; - } - - /** - * @return Returns the minimum length for a group name. - */ - public int getMinGroupNameLength() - { - return this.minGroupNameLength; - } - - /** - * @param minGroupNameLength The minimum length of a group name - */ - /*package*/ void setMinGroupNameLength(int minGroupNameLength) - { - this.minGroupNameLength = minGroupNameLength; - } - - /** - * Get the breadcrumb mode - * - * @return String - */ - public final String getBreadcrumbMode() - { - return breadcrumbMode; - } - - /** - * Set the breadcrumb mode - * - * @param mode String - */ - void setBreadcrumbMode(String mode) - { - // make sure it's being set to a valid option - if (BREADCRUMB_PATH.equals(mode) || BREADCRUMB_LOCATION.equals(mode)) - { - breadcrumbMode = mode; - } - } - - /** - * Get the CIFs URL suffix - * - * @return String - */ - public final String getCifsURLSuffix() - { - return cifsURLSuffix; - } - - /** - * Set the CIFS URL suffix - * - * @param suffix String - */ - void setCifsURLSuffix(String suffix) - { - cifsURLSuffix = suffix; - } - - /** - * @return the language select flag - true to display language selection, false to - * get the language from the client browser locale instead - */ - public final boolean isLanguageSelect() - { - return this.languageSelect; - } - - /** - * @param value the language select flag - */ - /*package*/ void setLanguageSelect(boolean value) - { - this.languageSelect = value; - } - - /** - * @return true if zero byte file uploads are allowed, false otherwise - */ - public boolean isZeroByteFileUploads() - { - return this.zeroByteFileUploads; - } - - /** - * @param zeroByteFileUploads true if zero byte file uploads are allowed, false otherwise - */ - /*package*/ void setZeroByteFileUploads(boolean zeroByteFileUploads) - { - this.zeroByteFileUploads = zeroByteFileUploads; - } - - /** - * @return true if allowing User Group administration by an admin user - */ - public boolean isUserGroupAdmin() - { - return this.userGroupAdmin; - } - - /** - * @param userGroupAdmin true to allow User Group administration by an admin user - */ - /*package*/ void setUserGroupAdmin(boolean userGroupAdmin) - { - this.userGroupAdmin = userGroupAdmin; - } - - /** - * @return true to allow users to modify their personal settings in the User Console screen - */ - public boolean getAllowUserConfig() - { - return this.allowUserConfig; - } - - /** - * @param allowUserConfig true to allow users to modify their personal settings in the User Console screen - */ - /*package*/ void setAllowUserConfig(boolean allowUserConfig) - { - this.allowUserConfig = allowUserConfig; - } - - /** - * @return Returns the minimum number of characters for a picker search. - */ - public int getPickerSearchMinimum() - { - return this.pickerSearchMinimum; - } - - /** - * @param searchMinimum The minimum number of characters for a picker search. - */ - /*package*/ void setPickerSearchMinimum(int searchMinimum) - { - this.pickerSearchMinimum = searchMinimum; - } - - /** - * @return true if the context path should be checked against the path in the current URL - */ - public boolean getCheckContextAgainstPath() - { - return this.checkContextAgainstPath; - } - - /** - * @param checkContextAgainstPath true to check the context path against the path in the current URL - */ - /*package*/ void setCheckContextAgainstPath(boolean checkContextAgainstPath) - { - this.checkContextAgainstPath = checkContextAgainstPath; - } - - /** - * @return true if any user can execute JavaScript via the command servlet - */ - public boolean getAllowUserScriptExecute() - { - return this.allowUserScriptExecute; - } - - /** - * @param allowUserScriptExecute true to allow any user to execute JavaScript via the command servlet - */ - /*package*/ void setAllowUserScriptExecute(boolean allowUserScriptExecute) - { - this.allowUserScriptExecute = allowUserScriptExecute; - } - - /** - * @return true if bulk fetch is enabled - */ - public boolean isBulkFetchEnabled() - { - return isBulkFetchEnabled; - } - - /** - * @param isBulkFetchEnabled boolean - */ - /*package*/ void setBulkFetchEnabled(boolean isBulkFetchEnabled) - { - this.isBulkFetchEnabled = isBulkFetchEnabled; - } - - /** - * @return regexp for email validation - */ - public String getEmailRegExp() - { - return emailRegExp; - } - -} diff --git a/war/src/main/java/org/alfresco/web/config/ClientElementReader.java b/war/src/main/java/org/alfresco/web/config/ClientElementReader.java deleted file mode 100644 index 3f79e3d5f1..0000000000 --- a/war/src/main/java/org/alfresco/web/config/ClientElementReader.java +++ /dev/null @@ -1,373 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - - -import java.util.ArrayList; -import java.util.List; - -import org.alfresco.service.namespace.QName; -import org.dom4j.Element; -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.xml.elementreader.ConfigElementReader; - -/** - * Custom element reader to parse config for client config values - * - * @author Kevin Roast - */ -public class ClientElementReader implements ConfigElementReader -{ - public static final String ELEMENT_RECENTSPACESITEMS = "recent-spaces-items"; - public static final String ELEMENT_ERRORPAGE = "error-page"; - public static final String ELEMENT_LOGINPAGE = "login-page"; - public static final String ELEMENT_HELPURL = "help-url"; - public static final String ELEMENT_EDITLINKTYPE = "edit-link-type"; - public static final String ELEMENT_SEARCHMINIMUM = "search-minimum"; - public static final String ELEMENT_SEARCHANDTERMS = "search-and-terms"; - public static final String ELEMENT_SEARCHMAXRESULTS = "search-max-results"; - public static final String ELEMENT_BULKFETCHENABLED = "bulk-fetch-enabled"; - public static final String ELEMENT_SELECTORSSEARCHMAXRESULTS = "selectors-search-max-results"; - public static final String ELEMENT_INVITESEARCHMAXRESULTS = "invite-users-max-results"; - public static final String ELEMENT_TASKSCOMPLETEDMAXRESULTS = "tasks-completed-max-results"; - public static final String ELEMENT_HOMESPACEPERMISSION = "home-space-permission"; - public static final String ELEMENT_FROMEMAILADDRESS = "from-email-address"; - public static final String ELEMENT_SHELFVISIBLE = "shelf-visible"; - public static final String ELEMENT_NODESUMMARY_ENABLED = "node-summary-enabled"; - public static final String ELEMENT_INITIALLOCATION = "initial-location"; - public static final String ELEMENT_DEFAULTHOMESPACEPATH = "default-home-space-path"; - public static final String ELEMENT_CLIPBOARDSTATUS = "clipboard-status-visible"; - public static final String ELEMENT_PASTEALLANDCLEAR = "paste-all-and-clear"; - public static final String ELEMENT_GUESTCONFIG = "allow-guest-config"; - public static final String ELEMENT_SIMPLESEARCHADDITIONALATTRS = "simple-search-additional-attributes"; - public static final String ELEMENT_SIMPLESEARCHADDITIONALATTRSQNAME = "qname"; - public static final String ELEMENT_MINUSERNAMELENGTH = "username-min-length"; - public static final String ELEMENT_MINPASSWORDLENGTH = "password-min-length"; - public static final String ELEMENT_MAXPASSWORDLENGTH = "password-max-length"; - public static final String ELEMENT_MINGROUPNAMELENGTH = "group-name-min-length"; - public static final String ELEMENT_BREADCRUMB_MODE = "breadcrumb-mode"; - public static final String ELEMENT_CIFSURLSUFFIX = "cifs-url-suffix"; - public static final String ELEMENT_LANGUAGESELECT = "language-select"; - public static final String ELEMENT_ZEROBYTEFILEUPLOADS = "zero-byte-file-uploads"; - public static final String ELEMENT_USERGROUPADMIN = "user-group-admin"; - public static final String ELEMENT_ALLOWUSERCONFIG = "allow-user-config"; - public static final String ELEMENT_PICKERSEARCHMINIMUM = "picker-search-minimum"; - public static final String ELEMENT_CHECKCONTEXTPATH = "check-context-against-path"; - public static final String ELEMENT_ALLOWUSERSCRIPTEXECUTE = "allow-user-script-execute"; - - - /** - * @see org.springframework.extensions.config.xml.elementreader.ConfigElementReader#parse(org.dom4j.Element) - */ - @SuppressWarnings("unchecked") - public ConfigElement parse(Element element) - { - ClientConfigElement configElement = null; - - if (element != null) - { - String name = element.getName(); - if (name.equals(ClientConfigElement.CONFIG_ELEMENT_ID) == false) - { - throw new ConfigException("ClientElementReader can only parse " + - ClientConfigElement.CONFIG_ELEMENT_ID + " elements, the element passed was '" + - name + "'"); - } - - configElement = new ClientConfigElement(); - - // get the recent space max items - Element recentSpaces = element.element(ELEMENT_RECENTSPACESITEMS); - if (recentSpaces != null) - { - configElement.setRecentSpacesItems(Integer.parseInt(recentSpaces.getTextTrim())); - } - - // get the shelf component default visibility - Element shelfVisible = element.element(ELEMENT_SHELFVISIBLE); - if (shelfVisible != null) - { - configElement.setShelfVisible(Boolean.parseBoolean(shelfVisible.getTextTrim())); - } - - // get the Help url - Element helpUrl = element.element(ELEMENT_HELPURL); - if (helpUrl != null) - { - configElement.setHelpUrl(helpUrl.getTextTrim()); - } - - // get the edit link type - Element editLinkType = element.element(ELEMENT_EDITLINKTYPE); - if (editLinkType != null) - { - configElement.setEditLinkType(editLinkType.getTextTrim()); - } - - // get the minimum number of characters for valid search string - Element searchMin = element.element(ELEMENT_SEARCHMINIMUM); - if (searchMin != null) - { - configElement.setSearchMinimum(Integer.parseInt(searchMin.getTextTrim())); - } - - // get the search force AND terms setting - Element searchForceAnd = element.element(ELEMENT_SEARCHANDTERMS); - if (searchForceAnd != null) - { - configElement.setForceAndTerms(Boolean.parseBoolean(searchForceAnd.getTextTrim())); - } - - // get the search max results size - Element searchMaxResults = element.element(ELEMENT_SEARCHMAXRESULTS); - if (searchMaxResults != null) - { - configElement.setSearchMaxResults(Integer.parseInt(searchMaxResults.getTextTrim())); - } - - // get the search max results size - Element isBulkFetchEnabled = element.element(ELEMENT_BULKFETCHENABLED); - if (isBulkFetchEnabled != null) - { - configElement.setBulkFetchEnabled(Boolean.parseBoolean(isBulkFetchEnabled.getTextTrim())); - } - - // get the selectors search max results size - Element selectorsSearchMaxResults = element.element(ELEMENT_SELECTORSSEARCHMAXRESULTS); - if (selectorsSearchMaxResults != null) - { - configElement.setSelectorsSearchMaxResults( - Integer.parseInt(selectorsSearchMaxResults.getTextTrim())); - } - - // get the invite users max results size - Element inviteUsersMaxResults = element.element(ELEMENT_INVITESEARCHMAXRESULTS); - if (inviteUsersMaxResults != null) - { - configElement.setInviteUsersMaxResults( - Integer.parseInt(inviteUsersMaxResults.getTextTrim())); - } - - // get the invite users max results size - Element completedTasksMaxResults = element.element(ELEMENT_TASKSCOMPLETEDMAXRESULTS); - if (completedTasksMaxResults != null) - { - configElement.setTasksCompletedMaxResults( - Integer.parseInt(completedTasksMaxResults.getTextTrim())); - } - - // get the default permission for newly created users Home Spaces - Element permission = element.element(ELEMENT_HOMESPACEPERMISSION); - if (permission != null) - { - configElement.setHomeSpacePermission(permission.getTextTrim()); - } - - // get the from address to use when sending emails from the client - Element fromEmail = element.element(ELEMENT_FROMEMAILADDRESS); - if (fromEmail != null) - { - configElement.setFromEmailAddress(fromEmail.getTextTrim()); - } - - // get the error page - Element errorPage = element.element(ELEMENT_ERRORPAGE); - if (errorPage != null) - { - configElement.setErrorPage(errorPage.getTextTrim()); - } - - // get the login page - Element loginPage = element.element(ELEMENT_LOGINPAGE); - if (loginPage != null) - { - configElement.setLoginPage(loginPage.getTextTrim()); - } - - // get the node summary popup enabled flag - Element ajaxEnabled = element.element(ELEMENT_NODESUMMARY_ENABLED); - if (ajaxEnabled != null) - { - configElement.setNodeSummaryEnabled(Boolean.parseBoolean(ajaxEnabled.getTextTrim())); - } - - // get the initial location - Element initialLocation = element.element(ELEMENT_INITIALLOCATION); - if (initialLocation != null) - { - configElement.setInitialLocation(initialLocation.getTextTrim()); - } - - // get the default home space path - Element defaultHomeSpacePath = element.element(ELEMENT_DEFAULTHOMESPACEPATH); - if (defaultHomeSpacePath != null) - { - configElement.setDefaultHomeSpacePath(defaultHomeSpacePath.getTextTrim()); - } - - // get the default visibility of the clipboard status messages - Element clipboardStatusVisible = element.element(ELEMENT_CLIPBOARDSTATUS); - if (clipboardStatusVisible != null) - { - configElement.setClipboardStatusVisible(Boolean.parseBoolean( - clipboardStatusVisible.getTextTrim())); - } - - // get the default setting for the paste all action, should it clear the clipboard after? - Element pasteAllAndClear = element.element(ELEMENT_PASTEALLANDCLEAR); - if (pasteAllAndClear != null) - { - configElement.setPasteAllAndClearEnabled(Boolean.parseBoolean( - pasteAllAndClear.getTextTrim())); - } - - // get allow Guest to configure start location preferences - Element guestConfigElement = element.element(ELEMENT_GUESTCONFIG); - if (guestConfigElement != null) - { - boolean allow = Boolean.parseBoolean(guestConfigElement.getTextTrim()); - configElement.setAllowGuestConfig(allow); - } - - // get the additional simple search attributes - Element simpleSearchAdditionalAttributesElement = element.element(ELEMENT_SIMPLESEARCHADDITIONALATTRS); - if (simpleSearchAdditionalAttributesElement != null) - { - List attrbElements = - simpleSearchAdditionalAttributesElement.elements(ELEMENT_SIMPLESEARCHADDITIONALATTRSQNAME); - if (attrbElements != null && attrbElements.size() != 0) - { - List simpleSearchAddtlAttrb = new ArrayList(4); - for (Element elem : attrbElements) - { - simpleSearchAddtlAttrb.add(QName.createQName(elem.getTextTrim())); - } - configElement.setSimpleSearchAdditionalAttributes(simpleSearchAddtlAttrb); - } - } - - // get the minimum length of usernames - Element minUsername = element.element(ELEMENT_MINUSERNAMELENGTH); - if (minUsername != null) - { - configElement.setMinUsernameLength(Integer.parseInt(minUsername.getTextTrim())); - } - - // get the minimum length of passwords - Element minPassword = element.element(ELEMENT_MINPASSWORDLENGTH); - if (minPassword != null) - { - configElement.setMinPasswordLength(Integer.parseInt(minPassword.getTextTrim())); - } - - // get the maximum length of passwords - Element maxPassword = element.element(ELEMENT_MAXPASSWORDLENGTH); - if (maxPassword != null) - { - configElement.setMaxPasswordLength(Integer.parseInt(maxPassword.getTextTrim())); - } - - // get the minimum length of group names - Element minGroupName = element.element(ELEMENT_MINGROUPNAMELENGTH); - if (minGroupName != null) - { - configElement.setMinGroupNameLength(Integer.parseInt(minGroupName.getTextTrim())); - } - - // get the breadcrumb mode - Element breadcrumbMode = element.element(ELEMENT_BREADCRUMB_MODE); - if (breadcrumbMode != null) - { - configElement.setBreadcrumbMode(breadcrumbMode.getTextTrim()); - } - - // Get the CIFS URL suffix - Element cifsSuffix = element.element(ELEMENT_CIFSURLSUFFIX); - if (cifsSuffix != null) - { - String suffix = cifsSuffix.getTextTrim(); - if (suffix.startsWith(".") == false) - { - suffix = "." + suffix; - } - configElement.setCifsURLSuffix( suffix); - } - - // get the language selection mode - Element langSelect = element.element(ELEMENT_LANGUAGESELECT); - if (langSelect != null) - { - configElement.setLanguageSelect(Boolean.parseBoolean(langSelect.getTextTrim())); - } - - // get the zero byte file upload mode - Element zeroByteFiles = element.element(ELEMENT_ZEROBYTEFILEUPLOADS); - if (zeroByteFiles != null) - { - configElement.setZeroByteFileUploads(Boolean.parseBoolean(zeroByteFiles.getTextTrim())); - } - - // get allow user group admin mode - Element userGroupAdmin = element.element(ELEMENT_USERGROUPADMIN); - if (userGroupAdmin != null) - { - configElement.setUserGroupAdmin(Boolean.parseBoolean(userGroupAdmin.getTextTrim())); - } - - // get allow user config mode - Element userConfig = element.element(ELEMENT_ALLOWUSERCONFIG); - if (userConfig != null) - { - configElement.setAllowUserConfig(Boolean.parseBoolean(userConfig.getTextTrim())); - } - - // get the minimum number of characters for valid picker search string - Element pickerSearchMin = element.element(ELEMENT_PICKERSEARCHMINIMUM); - if (pickerSearchMin != null) - { - configElement.setPickerSearchMinimum(Integer.parseInt(pickerSearchMin.getTextTrim())); - } - - // determine whether the JavaScript setContextPath method should - // check the path of the current URL - Element checkContextAgainstPath = element.element(ELEMENT_CHECKCONTEXTPATH); - if (checkContextAgainstPath != null) - { - configElement.setCheckContextAgainstPath(Boolean.parseBoolean(checkContextAgainstPath.getTextTrim())); - } - - // get allow any user to execute javascript via the command servlet - Element allowUserScriptExecute = element.element(ELEMENT_ALLOWUSERSCRIPTEXECUTE); - if (allowUserScriptExecute != null) - { - configElement.setAllowUserScriptExecute(Boolean.parseBoolean(allowUserScriptExecute.getTextTrim())); - } - } - - return configElement; - } -} diff --git a/war/src/main/java/org/alfresco/web/config/CommandServletConfigElement.java b/war/src/main/java/org/alfresco/web/config/CommandServletConfigElement.java deleted file mode 100644 index 00fdd14f4e..0000000000 --- a/war/src/main/java/org/alfresco/web/config/CommandServletConfigElement.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.element.ConfigElementAdapter; - -/** - * @author Kevin Roast - */ -public class CommandServletConfigElement extends ConfigElementAdapter -{ - public static final String CONFIG_ELEMENT_ID = "command-servlet"; - - private Map commandProcessors = new HashMap(4, 1.0f); - - /** - * Default constructor - */ - public CommandServletConfigElement() - { - super("command-servlet"); - } - - /** - * Constructor - * - * @param name Name of the element this config element represents - */ - public CommandServletConfigElement(String name) - { - super(name); - } - - /** - * @see org.springframework.extensions.config.element.ConfigElementAdapter#getChildren() - */ - public List getChildren() - { - throw new ConfigException("Reading the Command Servlet config via the generic interfaces is not supported"); - } - - /** - * @see org.springframework.extensions.config.element.ConfigElementAdapter#combine(org.springframework.extensions.config.ConfigElement) - */ - public ConfigElement combine(ConfigElement configElement) - { - CommandServletConfigElement newElement = (CommandServletConfigElement)configElement; - CommandServletConfigElement combinedElement = new CommandServletConfigElement(); - - for (String name : commandProcessors.keySet()) - { - combinedElement.addCommandProcessor(name, commandProcessors.get(name)); - } - for (String name : newElement.commandProcessors.keySet()) - { - combinedElement.addCommandProcessor(name, newElement.commandProcessors.get(name)); - } - - return combinedElement; - } - - /*package*/ void addCommandProcessor(String name, String className) - { - try - { - Class clazz = Class.forName(className); - commandProcessors.put(name, clazz); - } - catch (Throwable err) - { - throw new ConfigException("Unable to load command proccessor class: " + - className + " due to " + err.getMessage()); - } - } - - private void addCommandProcessor(String name, Class clazz) - { - commandProcessors.put(name, clazz); - } - - public Class getCommandProcessor(String name) - { - return commandProcessors.get(name); - } -} diff --git a/war/src/main/java/org/alfresco/web/config/CommandServletElementReader.java b/war/src/main/java/org/alfresco/web/config/CommandServletElementReader.java deleted file mode 100644 index d058554e46..0000000000 --- a/war/src/main/java/org/alfresco/web/config/CommandServletElementReader.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.util.Iterator; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.xml.elementreader.ConfigElementReader; -import org.dom4j.Element; - -/** - * @author Kevin Roast - */ -public class CommandServletElementReader implements ConfigElementReader -{ - public static final String ELEMENT_COMMANDPROCESSOR = "command-processor"; - public static final String ATTRIBUTE_NAME = "name"; - public static final String ATTRIBUTE_CLASS = "class"; - - /** - * @see org.springframework.extensions.config.xml.elementreader.ConfigElementReader#parse(org.dom4j.Element) - */ - @SuppressWarnings("unchecked") - public ConfigElement parse(Element element) - { - CommandServletConfigElement configElement = new CommandServletConfigElement(); - - if (element != null) - { - if (CommandServletConfigElement.CONFIG_ELEMENT_ID.equals(element.getName()) == false) - { - throw new ConfigException("CommandServletElementReader can only parse config elements of type 'command-servlet'"); - } - - Iterator itr = element.elementIterator(ELEMENT_COMMANDPROCESSOR); - while (itr.hasNext()) - { - Element procElement = itr.next(); - - String name = procElement.attributeValue(ATTRIBUTE_NAME); - String className = procElement.attributeValue(ATTRIBUTE_CLASS); - - if (name == null || name.length() == 0) - { - throw new ConfigException("'name' attribute is mandatory for command processor config element."); - } - if (className == null || className.length() == 0) - { - throw new ConfigException("'class' attribute is mandatory for command processor config element."); - } - - configElement.addCommandProcessor(name, className); - } - } - - return configElement; - } -} diff --git a/war/src/main/java/org/alfresco/web/config/ConfigAdminInterpreter.java b/war/src/main/java/org/alfresco/web/config/ConfigAdminInterpreter.java deleted file mode 100644 index 3648c19dd9..0000000000 --- a/war/src/main/java/org/alfresco/web/config/ConfigAdminInterpreter.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import java.util.List; - -import org.springframework.extensions.config.ConfigDeployment; -import org.springframework.extensions.surf.util.I18NUtil; -import org.alfresco.repo.admin.BaseInterpreter; -import org.alfresco.repo.config.xml.RepoXMLConfigService; -import org.alfresco.service.transaction.TransactionService; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; -import org.springframework.core.io.ClassPathResource; - -/** - * A simple interactive console for (first cut) Web Client Config Admin. - * - */ -public class ConfigAdminInterpreter extends BaseInterpreter -{ - // dependencies - private RepoXMLConfigService webClientConfigService; - - public void setRepoXMLConfigService(RepoXMLConfigService webClientConfigService) - { - this.webClientConfigService = webClientConfigService; - } - - public void setTransactionService(TransactionService transactionService) - { - this.transactionService = transactionService; - } - - /** - * Main entry point. - */ - public static void main(String[] args) - { - ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"classpath:alfresco/application-context.xml","classpath:alfresco/web-client-application-context.xml"}); - runMain(context, "webClientConfigAdminInterpreter"); - } - - /** - * Execute a single command using the BufferedReader passed in for any data needed. - * - * TODO: Use decent parser! - * - * @param line The unparsed command - * @return The textual output of the command. - */ - protected String executeCommand(String line) - throws IOException - { - String[] command = line.split(" "); - if (command.length == 0) - { - command = new String[1]; - command[0] = line; - } - - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - PrintStream out = new PrintStream(bout); - - // repeat last command? - if (command[0].equals("r")) - { - if (lastCommand == null) - { - return "No command entered yet."; - } - return "repeating command " + lastCommand + "\n\n" + executeCommand(lastCommand); - } - - // remember last command - lastCommand = line; - - // execute command - if (command[0].equals("help")) - { - String helpFile = I18NUtil.getMessage("configadmin_console.help"); - ClassPathResource helpResource = new ClassPathResource(helpFile); - byte[] helpBytes = new byte[500]; - InputStream helpStream = helpResource.getInputStream(); - try - { - int read = helpStream.read(helpBytes); - while (read != -1) - { - bout.write(helpBytes, 0, read); - read = helpStream.read(helpBytes); - } - } - finally - { - helpStream.close(); - } - } - - else if (command[0].equals("reload")) - { - if (command.length > 1) - { - return "Syntax Error.\n"; - } - - // destroy and re-initialise config service - webClientConfigService.destroy(); - List configDeployments = webClientConfigService.initConfig(); - - if (configDeployments != null) - { - out.println("Web Client config has been reloaded\n"); - - for (ConfigDeployment configDeployment : configDeployments) - { - out.println(configDeployment.getName() + " ---> " + configDeployment.getDeploymentStatus()); - } - } - else - { - out.println("No config reloaded"); - } - } - - else - { - return "No such command, try 'help'.\n"; - } - - out.flush(); - String retVal = new String(bout.toByteArray()); - out.close(); - return retVal; - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/config/DashboardsConfigElement.java b/war/src/main/java/org/alfresco/web/config/DashboardsConfigElement.java deleted file mode 100644 index a91fc28af1..0000000000 --- a/war/src/main/java/org/alfresco/web/config/DashboardsConfigElement.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.element.ConfigElementAdapter; - -/** - * Dashboard config element. - * - * @author Kevin Roast - */ -public class DashboardsConfigElement extends ConfigElementAdapter -{ - public static final String CONFIG_ELEMENT_ID = "dashboards"; - - private Map layoutDefs = new LinkedHashMap(4, 1.0f); - private Map dashletDefs = new LinkedHashMap(8, 1.0f); - private List defaultDashlets = null; - private boolean allowGuestConfig = false; - - /** - * Default constructor - */ - public DashboardsConfigElement() - { - super(CONFIG_ELEMENT_ID); - } - - /** - * @param name String - */ - public DashboardsConfigElement(String name) - { - super(name); - } - - /** - * @see org.springframework.extensions.config.element.ConfigElementAdapter#getChildren() - */ - public List getChildren() - { - throw new ConfigException("Reading the Dashboards config via the generic interfaces is not supported"); - } - - /** - * @see org.springframework.extensions.config.element.ConfigElementAdapter#combine(org.springframework.extensions.config.ConfigElement) - */ - public ConfigElement combine(ConfigElement configElement) - { - DashboardsConfigElement newElement = (DashboardsConfigElement)configElement; - DashboardsConfigElement combinedElement = new DashboardsConfigElement(); - - // put all into combined from this and then from new to override any already present - combinedElement.dashletDefs.putAll(this.dashletDefs); - combinedElement.dashletDefs.putAll(newElement.dashletDefs); - - combinedElement.layoutDefs.putAll(this.layoutDefs); - combinedElement.layoutDefs.putAll(newElement.layoutDefs); - - if (newElement.allowGuestConfig != combinedElement.allowGuestConfig) - { - combinedElement.allowGuestConfig = newElement.allowGuestConfig; - } - - // the default-dashlets list is completely replaced if config is overriden - if (newElement.defaultDashlets != null) - { - combinedElement.defaultDashlets = - (List)((ArrayList)newElement.defaultDashlets).clone(); - } - else if (this.defaultDashlets != null) - { - combinedElement.defaultDashlets = - (List)((ArrayList)this.defaultDashlets).clone(); - } - - return combinedElement; - } - - /*package*/ void setAllowGuestConfig(boolean allow) - { - this.allowGuestConfig = allow; - } - - public boolean getAllowGuestConfig() - { - return this.allowGuestConfig; - } - - /*package*/ void addLayoutDefinition(LayoutDefinition def) - { - this.layoutDefs.put(def.Id, def); - } - - public LayoutDefinition getLayoutDefinition(String id) - { - return this.layoutDefs.get(id); - } - - /*package*/ void addDashletDefinition(DashletDefinition def) - { - this.dashletDefs.put(def.Id, def); - } - - public DashletDefinition getDashletDefinition(String id) - { - return this.dashletDefs.get(id); - } - - public Collection getLayouts() - { - return this.layoutDefs.values(); - } - - public Collection getDashlets() - { - return this.dashletDefs.values(); - } - - /*package*/ void addDefaultDashlet(String id) - { - if (this.defaultDashlets == null) - { - this.defaultDashlets = new ArrayList(2); - } - this.defaultDashlets.add(id); - } - - public Collection getDefaultDashlets() - { - return this.defaultDashlets; - } - - /** - * Structure class for the definition of a dashboard page layout - */ - public static class LayoutDefinition implements Serializable - { - private static final long serialVersionUID = -3014156293576142077L; - - LayoutDefinition(String id) - { - this.Id = id; - } - - public String Id; - public String Image; - public int Columns; - public int ColumnLength; - public String Label; - public String LabelId; - public String Description; - public String DescriptionId; - public String JSPPage; - } - - /** - * Structure class for the definition of a dashboard dashlet component - */ - public static class DashletDefinition implements Serializable - { - private static final long serialVersionUID = -5755903997700459631L; - - DashletDefinition(String id) - { - this.Id = id; - } - - public String Id; - public boolean AllowNarrow = true; - public String Label; - public String LabelId; - public String Description; - public String DescriptionId; - public String JSPPage; - public String ConfigJSPPage; - } -} diff --git a/war/src/main/java/org/alfresco/web/config/DashboardsElementReader.java b/war/src/main/java/org/alfresco/web/config/DashboardsElementReader.java deleted file mode 100644 index cc72459da2..0000000000 --- a/war/src/main/java/org/alfresco/web/config/DashboardsElementReader.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.util.Iterator; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.xml.elementreader.ConfigElementReader; -import org.alfresco.web.config.DashboardsConfigElement.DashletDefinition; -import org.alfresco.web.config.DashboardsConfigElement.LayoutDefinition; -import org.dom4j.Element; - -/** - * Reader for the 'dashboards' config element and child elements. - * - * @author Kevin Roast - */ -public class DashboardsElementReader implements ConfigElementReader -{ - public static final String ELEMENT_DASHBOARDS = "dashboards"; - public static final String ELEMENT_LAYOUTS = "layouts"; - public static final String ELEMENT_LAYOUT = "layout"; - public static final String ELEMENT_DASHLETS = "dashlets"; - public static final String ELEMENT_DASHLET = "dashlet"; - public static final String ELEMENT_GUESTCONFIG = "allow-guest-config"; - public static final String ELEMENT_DEFAULTDASHLETS = "default-dashlets"; - public static final String ATTR_ID = "id"; - public static final String ATTR_COLUMNS = "columns"; - public static final String ATTR_COLUMNLENGTH = "column-length"; - public static final String ATTR_IMAGE = "image"; - public static final String ATTR_LABEL = "label"; - public static final String ATTR_DESCRIPTION = "description"; - public static final String ATTR_LABELID = "label-id"; - public static final String ATTR_DESCRIPTIONID = "description-id"; - public static final String ATTR_JSP = "jsp"; - public static final String ATTR_CONFIGJSP = "config-jsp"; - public static final String ATTR_ALLOWNARROW = "allow-narrow"; - - /** - * @see org.springframework.extensions.config.xml.elementreader.ConfigElementReader#parse(org.dom4j.Element) - */ - @SuppressWarnings("unchecked") - public ConfigElement parse(Element element) - { - DashboardsConfigElement configElement = new DashboardsConfigElement(); - - if (element != null) - { - if (DashboardsConfigElement.CONFIG_ELEMENT_ID.equals(element.getName()) == false) - { - throw new ConfigException("DashboardsElementReader can only process elements of type 'dashboards'"); - } - - Element layoutsElement = element.element(ELEMENT_LAYOUTS); - if (layoutsElement != null) - { - Iterator layoutsItr = layoutsElement.elementIterator(ELEMENT_LAYOUT); - while (layoutsItr.hasNext()) - { - LayoutDefinition layoutDef = parseLayoutDefinition(layoutsItr.next()); - configElement.addLayoutDefinition(layoutDef); - } - } - - Element dashletsElement = element.element(ELEMENT_DASHLETS); - if (dashletsElement != null) - { - Iterator dashletsItr = dashletsElement.elementIterator(ELEMENT_DASHLET); - while (dashletsItr.hasNext()) - { - DashletDefinition dashletDef = parseDashletDefinition(dashletsItr.next()); - configElement.addDashletDefinition(dashletDef); - } - } - - Element defaultDashletsElement = element.element(ELEMENT_DEFAULTDASHLETS); - if (defaultDashletsElement != null) - { - Iterator dashletsItr = defaultDashletsElement.elementIterator(ELEMENT_DASHLET); - while (dashletsItr.hasNext()) - { - String id = getMandatoryDashletAttributeValue(dashletsItr.next(), ATTR_ID); - configElement.addDefaultDashlet(id); - } - } - - Element guestConfigElement = element.element(ELEMENT_GUESTCONFIG); - if (guestConfigElement != null) - { - boolean allow = Boolean.parseBoolean(guestConfigElement.getTextTrim()); - configElement.setAllowGuestConfig(allow); - } - } - - return configElement; - } - - /** - * Parse a single Layout definition from config. - * - * @param config Element - * - * @return LayoutDefinition for the specified config element. - */ - private static LayoutDefinition parseLayoutDefinition(Element config) - { - String id = getMandatoryLayoutAttributeValue(config, ATTR_ID); - - LayoutDefinition def = new LayoutDefinition(id); - - String columns = getMandatoryLayoutAttributeValue(config, ATTR_COLUMNS); - def.Columns = Integer.parseInt(columns); - String columnLength = getMandatoryLayoutAttributeValue(config, ATTR_COLUMNLENGTH); - def.ColumnLength = Integer.parseInt(columnLength); - def.Image = getMandatoryLayoutAttributeValue(config, ATTR_IMAGE); - def.JSPPage = getMandatoryLayoutAttributeValue(config, ATTR_JSP); - String label = config.attributeValue(ATTR_LABEL); - String labelId = config.attributeValue(ATTR_LABELID); - if ((label == null || label.length() == 0) && (labelId == null || labelId.length() == 0)) - { - throw new ConfigException("Either 'label' or 'label-id' attribute must be specified for Dashboard 'layout' configuration element."); - } - def.Label = label; - def.LabelId = labelId; - String description = config.attributeValue(ATTR_DESCRIPTION); - String descriptionId = config.attributeValue(ATTR_DESCRIPTIONID); - if ((description == null || description.length() == 0) && (descriptionId == null || descriptionId.length() == 0)) - { - throw new ConfigException("Either 'description' or 'description-id' attribute must be specified for Dashboard 'layout' configuration element."); - } - def.Description = description; - def.DescriptionId = descriptionId; - - return def; - } - - /** - * Return a mandatory layout attribute layout. Throw an exception if the value is not found. - * - * @param config Element - * @param attr String - * - * @return String value - */ - private static String getMandatoryLayoutAttributeValue(Element config, String attr) - { - String value = config.attributeValue(attr); - if (value == null || value.length() == 0) - { - throw new ConfigException("Missing mandatory '" + attr + "' attribute for Dashboard 'layout' configuration element."); - } - return value; - } - - /** - * Parse a single Dashlet definition from config. - * - * @param config Element - * - * @return DashletDefinition for the specified config element. - */ - private static DashletDefinition parseDashletDefinition(Element config) - { - String id = getMandatoryDashletAttributeValue(config, ATTR_ID); - - DashletDefinition def = new DashletDefinition(id); - - String allowNarrow = config.attributeValue(ATTR_ALLOWNARROW); - if (allowNarrow != null && allowNarrow.length() != 0) - { - def.AllowNarrow = Boolean.parseBoolean(allowNarrow); - } - def.JSPPage = getMandatoryDashletAttributeValue(config, ATTR_JSP); - def.ConfigJSPPage = config.attributeValue(ATTR_CONFIGJSP); - String label = config.attributeValue(ATTR_LABEL); - String labelId = config.attributeValue(ATTR_LABELID); - if ((label == null || label.length() == 0) && (labelId == null || labelId.length() == 0)) - { - throw new ConfigException("Either 'label' or 'label-id' attribute must be specified for Dashboard 'dashlet' configuration element."); - } - def.Label = label; - def.LabelId = labelId; - String description = config.attributeValue(ATTR_DESCRIPTION); - String descriptionId = config.attributeValue(ATTR_DESCRIPTIONID); - if ((description == null || description.length() == 0) && (descriptionId == null || descriptionId.length() == 0)) - { - throw new ConfigException("Either 'description' or 'description-id' attribute must be specified for Dashboard 'dashlet' configuration element."); - } - def.Description = description; - def.DescriptionId = descriptionId; - - return def; - } - - /** - * Return a mandatory dashlet attribute layout. Throw an exception if the value is not found. - * - * @param config Element - * @param attr String - * - * @return String value - */ - private static String getMandatoryDashletAttributeValue(Element config, String attr) - { - String value = config.attributeValue(attr); - if (value == null || value.length() == 0) - { - throw new ConfigException("Missing mandatory '" + attr + "' attribute for Dashboard 'dashlet' configuration element."); - } - return value; - } -} diff --git a/war/src/main/java/org/alfresco/web/config/DialogsConfigElement.java b/war/src/main/java/org/alfresco/web/config/DialogsConfigElement.java deleted file mode 100644 index c004d3ae38..0000000000 --- a/war/src/main/java/org/alfresco/web/config/DialogsConfigElement.java +++ /dev/null @@ -1,620 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.io.Serializable; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.element.ConfigElementAdapter; -import org.springframework.extensions.surf.util.ParameterCheck; - -/** - * Custom config element that represents the config data for a property sheet - * - * @author gavinc - */ -public class DialogsConfigElement extends ConfigElementAdapter -{ - private static final long serialVersionUID = 8265738244249506534L; - - public static final String CONFIG_ELEMENT_ID = "dialogs"; - - private Map dialogs = new LinkedHashMap(8, 10f); - - /** - * Default constructor - */ - public DialogsConfigElement() - { - super(CONFIG_ELEMENT_ID); - } - - /** - * Constructor - * - * @param name Name of the element this config element represents - */ - public DialogsConfigElement(String name) - { - super(name); - } - - /** - * @see ConfigElement#getChildren() - */ - public List getChildren() - { - throw new ConfigException("Reading the dialogs config via the generic interfaces is not supported"); - } - - /** - * @see ConfigElement#combine(org.springframework.extensions.config.ConfigElement) - */ - public ConfigElement combine(ConfigElement configElement) - { - DialogsConfigElement combined = new DialogsConfigElement(); - - // add all the dialogs from this element - for (DialogConfig dialog : this.getDialogs().values()) - { - combined.addDialog(dialog); - } - - // add all the dialogs from the given element - for (DialogConfig dialog : ((DialogsConfigElement)configElement).getDialogs().values()) - { - combined.addDialog(dialog); - } - - return combined; - } - - /** - * Returns the named dialog - * - * @param name The name of the dialog to retrieve - * @return The DialogConfig object for the requested dialog or null if it doesn't exist - */ - public DialogConfig getDialog(String name) - { - return this.dialogs.get(name); - } - - /** - * @return Returns a map of the dialogs. A linked hash map is used internally to - * preserve ordering. - */ - public Map getDialogs() - { - return this.dialogs; - } - - /** - * Adds a dialog - * - * @param dialogConfig A pre-configured dialog config object - */ - /*package*/ void addDialog(DialogConfig dialogConfig) - { - this.dialogs.put(dialogConfig.getName(), dialogConfig); - } - - /** - * Immutable inner class representing the configuration of a single dialog. - * - * @author gavinc - */ - public static class DialogConfig implements Serializable - { - private static final long serialVersionUID = -3163053165721862390L; - - protected DialogAttributes attributes; - - public DialogConfig(DialogAttributes attrs) - { - // check the attributes object has been supplied - ParameterCheck.mandatory("attrs", attrs); - - this.attributes = attrs; - } - - public String getName() - { - return this.attributes.getName(); - } - - public String getPage() - { - return this.attributes.getPage(); - } - - public String getManagedBean() - { - return this.attributes.getManagedBean(); - } - - public String getTitle() - { - return this.attributes.getTitle(); - } - - public String getTitleId() - { - return this.attributes.getTitleId(); - } - - public String getSubTitle() - { - return this.attributes.getSubTitle(); - } - - public String getSubTitleId() - { - return this.attributes.getSubTitleId(); - } - - public String getDescription() - { - return this.attributes.getDescription(); - } - - public String getDescriptionId() - { - return this.attributes.getDescriptionId(); - } - - public String getIcon() - { - return this.attributes.getIcon(); - } - - public String getErrorMessageId() - { - return this.attributes.getErrorMessageId(); - } - - public boolean isOKButtonVisible() - { - return this.attributes.isOKButtonVisible(); - } - - public List getButtons() - { - return this.attributes.getButtons(); - } - - public String getActionsConfigId() - { - return this.attributes.getActionsConfigId(); - } - - public boolean getActionsAsMenu() - { - return this.attributes.getActionsAsMenu(); - } - - public String getActionsMenuLabel() - { - return this.attributes.getActionsMenuLabel(); - } - - public String getActionsMenuLabelId() - { - return this.attributes.getActionsMenuLabelId(); - } - - public String getMoreActionsConfigId() - { - return this.attributes.getMoreActionsConfigId(); - } - - public String getMoreActionsMenuLabel() - { - return this.attributes.getMoreActionsMenuLabel(); - } - - public String getMoreActionsMenuLabelId() - { - return this.attributes.getMoreActionsMenuLabelId(); - } - - /** - * @see java.lang.Object#toString() - */ - @Override - public String toString() - { - StringBuilder buffer = new StringBuilder(super.toString()); - buffer.append(" (").append(this.attributes.toString()).append(")"); - return buffer.toString(); - } - } - - /** - * Immutable inner class representing the configuration for an additional - * dialog button. - * - * @author gavinc - */ - public static class DialogButtonConfig implements Serializable - { - private static final long serialVersionUID = -6897300549206163138L; - - private String id; - private String label; - private String labelId; - private String action; - private String disabled; - private String onclick; - - public DialogButtonConfig(String id, String label, String labelId, - String action, String disabled, String onclick) - { - this.id = id; - this.label = label; - this.labelId = labelId; - this.action = action; - this.disabled = disabled; - this.onclick = onclick; - - if ((this.label == null || this.label.length() == 0) && - (this.labelId == null || this.labelId.length() == 0)) - { - throw new ConfigException("A dialog button needs to have a label or a label-id"); - } - - if (this.action == null || this.action.length() == 0) - { - throw new ConfigException("A dialog button requires an action"); - } - else if (this.action.startsWith("#{") == false) - { - throw new ConfigException("The action for a dialog button must be a method binding expression, '" - + this.action + "' is not!"); - } - } - - public String getAction() - { - return action; - } - - public String getDisabled() - { - return disabled; - } - - public String getId() - { - return id; - } - - public String getLabel() - { - return label; - } - - public String getLabelId() - { - return labelId; - } - - public String getOnclick() - { - return onclick; - } - - /** - * @see java.lang.Object#toString() - */ - @Override - public String toString() - { - StringBuilder buffer = new StringBuilder(super.toString()); - buffer.append(" (id=").append(this.id); - buffer.append(" label=").append(this.label); - buffer.append(" label-id=").append(this.labelId); - buffer.append(" action=").append(this.action); - buffer.append(" disabled=").append(this.disabled); - buffer.append(" onclick=").append(this.onclick).append(")"); - return buffer.toString(); - } - } - - /** - * Object holding all the dialog attributes collected from config. - * - * @author gavinc - */ - public static class DialogAttributes implements Serializable - { - private static final long serialVersionUID = -6897300549207773138L; - - protected String name; - protected String page; - protected String managedBean; - protected String icon; - protected String title; - protected String titleId; - protected String subTitle; - protected String subTitleId; - protected String description; - protected String descriptionId; - protected String errorMsgId = "error_dialog"; - protected boolean isOKButtonVisible = true; - protected List buttons; - protected String actionsConfigId; - protected boolean actionsAsMenu = false; - protected String actionsMenuLabel; - protected String actionsMenuLabelId; - protected String moreActionsConfigId; - protected String moreActionsMenuLabel; - protected String moreActionsMenuLabelId; - - // ---------------------------------------------------- - // Construction - - public DialogAttributes(String name, String page, String bean) - { - // check the mandatory parameters are present - ParameterCheck.mandatoryString("name", name); - ParameterCheck.mandatoryString("page", page); - ParameterCheck.mandatoryString("managedBean", bean); - - this.name = name; - this.page = page; - this.managedBean = bean; - } - - // ---------------------------------------------------- - // Setters - - public void setIcon(String icon) - { - this.icon = icon; - } - - public void setTitle(String title) - { - this.title = title; - } - - public void setTitleId(String titleId) - { - this.titleId = titleId; - } - - public void setSubTitle(String subTitle) - { - this.subTitle = subTitle; - } - - public void setSubTitleId(String subTitleId) - { - this.subTitleId = subTitleId; - } - - public void setDescription(String description) - { - this.description = description; - } - - public void setDescriptionId(String descriptionId) - { - this.descriptionId = descriptionId; - } - - public void setErrorMessageId(String errorMsgId) - { - if (errorMsgId != null && errorMsgId.length() > 0) - { - this.errorMsgId = errorMsgId; - } - } - - public void setOKButtonVisible(boolean isOKButtonVisible) - { - this.isOKButtonVisible = isOKButtonVisible; - } - - public void setButtons(List buttons) - { - this.buttons = buttons; - } - - public void setActionsConfigId(String actionsConfigId) - { - this.actionsConfigId = actionsConfigId; - } - - public void setActionsAsMenu(boolean actionsAsMenu) - { - this.actionsAsMenu = actionsAsMenu; - } - - public void setActionsMenuLabel(String actionsMenuLabel) - { - this.actionsMenuLabel = actionsMenuLabel; - } - - public void setActionsMenuLabelId(String actionsMenuLabelId) - { - this.actionsMenuLabelId = actionsMenuLabelId; - } - - public void setMoreActionsConfigId(String moreActionsConfigId) - { - this.moreActionsConfigId = moreActionsConfigId; - } - - public void setMoreActionsMenuLabel(String moreActionsMenuLabel) - { - this.moreActionsMenuLabel = moreActionsMenuLabel; - } - - public void setMoreActionsMenuLabelId(String moreActionsMenuLabelId) - { - this.moreActionsMenuLabelId = moreActionsMenuLabelId; - } - - // ---------------------------------------------------- - // Getters - - public String getName() - { - return this.name; - } - - public String getPage() - { - return this.page; - } - - public String getManagedBean() - { - return this.managedBean; - } - - public String getDescription() - { - return this.description; - } - - public String getDescriptionId() - { - return this.descriptionId; - } - - public String getIcon() - { - return this.icon; - } - - public String getTitle() - { - return this.title; - } - - public String getTitleId() - { - return this.titleId; - } - - public String getSubTitle() - { - return this.subTitle; - } - - public String getSubTitleId() - { - return this.subTitleId; - } - - public String getErrorMessageId() - { - return this.errorMsgId; - } - - public boolean isOKButtonVisible() - { - return this.isOKButtonVisible; - } - - public List getButtons() - { - return this.buttons; - } - - public String getActionsConfigId() - { - return this.actionsConfigId; - } - - public boolean getActionsAsMenu() - { - return this.actionsAsMenu; - } - - public String getActionsMenuLabel() - { - return this.actionsMenuLabel; - } - - public String getActionsMenuLabelId() - { - return this.actionsMenuLabelId; - } - - public String getMoreActionsConfigId() - { - return this.moreActionsConfigId; - } - - public String getMoreActionsMenuLabel() - { - return this.moreActionsMenuLabel; - } - - public String getMoreActionsMenuLabelId() - { - return this.moreActionsMenuLabelId; - } - - /** - * @see java.lang.Object#toString() - */ - @Override - public String toString() - { - StringBuilder buffer = new StringBuilder(); - buffer.append("name=").append(this.name); - buffer.append(" page=").append(this.page); - buffer.append(" managedBean=").append(this.managedBean); - buffer.append(" icon=").append(this.icon); - buffer.append(" title=").append(this.title); - buffer.append(" titleId=").append(this.titleId); - buffer.append(" subTitle=").append(this.subTitle); - buffer.append(" subTitleId=").append(this.subTitleId); - buffer.append(" description=").append(this.description); - buffer.append(" descriptionId=").append(this.descriptionId); - buffer.append(" errorMsgId=").append(this.errorMsgId); - buffer.append(" isOKButtonVisible=").append(this.isOKButtonVisible); - buffer.append(" actionsConfigId=").append(this.actionsConfigId); - buffer.append(" actionsAsMenu=").append(this.actionsAsMenu); - buffer.append(" actionsMenuLabel=").append(this.actionsMenuLabel); - buffer.append(" actionsMenuLabelId=").append(this.actionsMenuLabelId); - buffer.append(" moreActionsConfigId=").append(this.moreActionsConfigId); - buffer.append(" moreActionsMenuLabel=").append(this.moreActionsMenuLabel); - buffer.append(" moreActionsMenuLabelId=").append(this.moreActionsMenuLabelId); - buffer.append(" buttons=").append(this.buttons); - return buffer.toString(); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/config/DialogsElementReader.java b/war/src/main/java/org/alfresco/web/config/DialogsElementReader.java deleted file mode 100644 index b34755c35f..0000000000 --- a/war/src/main/java/org/alfresco/web/config/DialogsElementReader.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.xml.elementreader.ConfigElementReader; -import org.alfresco.web.config.DialogsConfigElement.DialogButtonConfig; -import org.dom4j.Element; - -/** - * Custom element reader to parse config for dialogs - * - * @author gavinc - */ -public class DialogsElementReader implements ConfigElementReader -{ - public static final String ELEMENT_DIALOGS = "dialogs"; - public static final String ELEMENT_DIALOG = "dialog"; - public static final String ELEMENT_BUTTONS = "buttons"; - public static final String ELEMENT_BUTTON = "button"; - public static final String ATTR_NAME = "name"; - public static final String ATTR_PAGE = "page"; - public static final String ATTR_MANAGED_BEAN = "managed-bean"; - public static final String ATTR_ICON = "icon"; - public static final String ATTR_TITLE = "title"; - public static final String ATTR_TITLE_ID = "title-id"; - public static final String ATTR_SUBTITLE = "subtitle"; - public static final String ATTR_SUBTITLE_ID = "subtitle-id"; - public static final String ATTR_DESCRIPTION = "description"; - public static final String ATTR_DESCRIPTION_ID = "description-id"; - public static final String ATTR_ERROR_MSG_ID = "error-message-id"; - public static final String ATTR_SHOW_OK_BUTTON = "show-ok-button"; - - // action related attributes - public static final String ATTR_ACTIONS_CONFIG_ID = "actions-config-id"; - public static final String ATTR_ACTIONS_AS_MENU = "actions-as-menu"; - public static final String ATTR_ACTIONS_MENU_LABEL = "actions-menu-label"; - public static final String ATTR_ACTIONS_MENU_LABEL_ID = "actions-menu-label-id"; - public static final String ATTR_MORE_ACTIONS_CONFIG_ID = "more-actions-config-id"; - public static final String ATTR_MORE_ACTIONS_MENU_LABEL = "more-actions-menu-label"; - public static final String ATTR_MORE_ACTIONS_MENU_LABEL_ID = "more-actions-menu-label-id"; - - // button related attributes - public static final String ATTR_ID = "id"; - public static final String ATTR_LABEL = "label"; - public static final String ATTR_LABEL_ID = "label-id"; - public static final String ATTR_ACTION = "action"; - public static final String ATTR_DISABLED = "disabled"; - public static final String ATTR_ONCLICK = "onclick"; - - /** - * @see org.springframework.extensions.config.xml.elementreader.ConfigElementReader#parse(org.dom4j.Element) - */ - @SuppressWarnings("unchecked") - public ConfigElement parse(Element element) - { - DialogsConfigElement configElement = null; - - if (element != null) - { - String elementName = element.getName(); - if (elementName.equals(ELEMENT_DIALOGS) == false) - { - throw new ConfigException("DialogsElementReader can only parse " + - ELEMENT_DIALOGS + "elements, the element passed was '" + - elementName + "'"); - } - - configElement = new DialogsConfigElement(); - - // go through the dialogs - Iterator items = element.elementIterator(ELEMENT_DIALOG); - while (items.hasNext()) - { - Element item = items.next(); - - String name = item.attributeValue(ATTR_NAME); - String page = item.attributeValue(ATTR_PAGE); - String bean = item.attributeValue(ATTR_MANAGED_BEAN); - String icon = item.attributeValue(ATTR_ICON); - String title = item.attributeValue(ATTR_TITLE); - String titleId = item.attributeValue(ATTR_TITLE_ID); - String subTitle = item.attributeValue(ATTR_SUBTITLE); - String subTitleId = item.attributeValue(ATTR_SUBTITLE_ID); - String description = item.attributeValue(ATTR_DESCRIPTION); - String descriptionId = item.attributeValue(ATTR_DESCRIPTION_ID); - String errorMsgId = item.attributeValue(ATTR_ERROR_MSG_ID); - String showOK = item.attributeValue(ATTR_SHOW_OK_BUTTON); - - boolean isOKButtonVisible = true; - if (showOK != null) - { - isOKButtonVisible = Boolean.parseBoolean(showOK); - } - - // action related config - String actionsConfigId = item.attributeValue(ATTR_ACTIONS_CONFIG_ID); - boolean useMenuForActions = false; - String asMenu = item.attributeValue(ATTR_ACTIONS_AS_MENU); - if (asMenu != null) - { - useMenuForActions = Boolean.parseBoolean(asMenu); - } - String actionsMenuLabel = item.attributeValue(ATTR_ACTIONS_MENU_LABEL); - String actionsMenuLabelId = item.attributeValue(ATTR_ACTIONS_MENU_LABEL_ID); - String moreActionsConfigId = item.attributeValue(ATTR_MORE_ACTIONS_CONFIG_ID); - String moreActionsMenuLabel = item.attributeValue(ATTR_MORE_ACTIONS_MENU_LABEL); - String moreActionsMenuLabelId = item.attributeValue(ATTR_MORE_ACTIONS_MENU_LABEL_ID); - - // parse any buttons that may be present - List buttons = parseButtons(item); - - // setup the attrbiutes object - DialogsConfigElement.DialogAttributes attrs = - new DialogsConfigElement.DialogAttributes(name, page, bean); - attrs.setIcon(icon); - attrs.setTitle(title); - attrs.setTitleId(titleId); - attrs.setSubTitle(subTitle); - attrs.setSubTitleId(subTitleId); - attrs.setDescription(description); - attrs.setDescriptionId(descriptionId); - attrs.setErrorMessageId(errorMsgId); - attrs.setOKButtonVisible(isOKButtonVisible); - attrs.setButtons(buttons); - attrs.setActionsConfigId(actionsConfigId); - attrs.setActionsAsMenu(useMenuForActions); - attrs.setActionsMenuLabel(actionsMenuLabel); - attrs.setActionsMenuLabelId(actionsMenuLabelId); - attrs.setMoreActionsConfigId(moreActionsConfigId); - attrs.setMoreActionsMenuLabel(moreActionsMenuLabel); - attrs.setMoreActionsMenuLabelId(moreActionsMenuLabelId); - - // create and add the dialog config object - DialogsConfigElement.DialogConfig cfg = new DialogsConfigElement.DialogConfig(attrs); - configElement.addDialog(cfg); - } - } - - return configElement; - } - - /** - * Retrieve the configuration for additional buttons. - * - * @param dialog The dialog XML element - * @return List of configured buttons - */ - @SuppressWarnings("unchecked") - protected List parseButtons(Element dialog) - { - List buttons = null; - - // iterate over any configured buttons - Element buttonsConfig = dialog.element(ELEMENT_BUTTONS); - if (buttonsConfig != null) - { - buttons = new ArrayList(4); - - Iterator children = buttonsConfig.elementIterator(ELEMENT_BUTTON); - while (children.hasNext()) - { - Element button = children.next(); - - String id = button.attributeValue(ATTR_ID); - String label = button.attributeValue(ATTR_LABEL); - String labelId = button.attributeValue(ATTR_LABEL_ID); - String action = button.attributeValue(ATTR_ACTION); - String disabled = button.attributeValue(ATTR_DISABLED); - String onclick = button.attributeValue(ATTR_ONCLICK); - - // create the button config object - DialogButtonConfig btnCfg = new DialogButtonConfig(id, label, - labelId, action, disabled, onclick); - - // add the button to the list - buttons.add(btnCfg); - } - } - - return buttons; - } -} diff --git a/war/src/main/java/org/alfresco/web/config/LanguagesConfigElement.java b/war/src/main/java/org/alfresco/web/config/LanguagesConfigElement.java deleted file mode 100644 index 2164b4836f..0000000000 --- a/war/src/main/java/org/alfresco/web/config/LanguagesConfigElement.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.element.ConfigElementAdapter; - -/** - * Custom config element that represents config values for languages - * - * @author Gavin Cornwell - */ -public class LanguagesConfigElement extends ConfigElementAdapter -{ - public static final String CONFIG_ELEMENT_ID = "languages"; - - private Map localeMap = new HashMap(); - private List languages = new ArrayList(8); - - /** - * Default Constructor - */ - public LanguagesConfigElement() - { - super(CONFIG_ELEMENT_ID); - } - - /** - * Constructor - * - * @param name Name of the element this config element represents - */ - public LanguagesConfigElement(String name) - { - super(name); - } - - /** - * @see org.springframework.extensions.config.element.ConfigElementAdapter#getChildren() - */ - @Override - public List getChildren() - { - throw new ConfigException("Reading the languages config via the generic interfaces is not supported"); - } - - /** - * @see org.springframework.extensions.config.element.ConfigElementAdapter#combine(org.springframework.extensions.config.ConfigElement) - */ - public ConfigElement combine(ConfigElement configElement) - { - LanguagesConfigElement newElement = (LanguagesConfigElement)configElement; - LanguagesConfigElement combinedElement = new LanguagesConfigElement(); - - // add the languages from this config element - for (String locale : this.languages) - { - combinedElement.addLanguage(locale, this.localeMap.get(locale)); - } - - // now add the languages from the one to be combined (but - // only if they are not already in the list) - List languages = newElement.getLanguages(); - for (String locale : languages) - { - if (combinedElement.getLabelForLanguage(locale) == null) - { - String label = newElement.getLabelForLanguage(locale); - combinedElement.addLanguage(locale, label); - } - } - - return combinedElement; - } - - /** - * Add a language locale and display label to the list. - * - * @param locale Locale code - * @param label Display label - */ - /*package*/ void addLanguage(String locale, String label) - { - this.localeMap.put(locale, label); - this.languages.add(locale); - } - - /** - * @return List of supported language locale strings in config file order - */ - public List getLanguages() - { - return this.languages; - } - - /** - * @param locale The locale string to lookup language label for - * - * @return the language label for specified locale string, or null if not found - */ - public String getLabelForLanguage(String locale) - { - return this.localeMap.get(locale); - } -} diff --git a/war/src/main/java/org/alfresco/web/config/LanguagesElementReader.java b/war/src/main/java/org/alfresco/web/config/LanguagesElementReader.java deleted file mode 100644 index 9fd606dab0..0000000000 --- a/war/src/main/java/org/alfresco/web/config/LanguagesElementReader.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.util.Iterator; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.xml.elementreader.ConfigElementReader; -import org.dom4j.Element; - -/** - * Custom element reader to parse config for languages - * - * @author Gavin Cornwell - */ -public class LanguagesElementReader implements ConfigElementReader -{ - public static final String ELEMENT_LANGUAGE = "language"; - public static final String ATTRIBUTE_LOCALE = "locale"; - - /** - * @see org.springframework.extensions.config.xml.elementreader.ConfigElementReader#parse(org.dom4j.Element) - */ - @SuppressWarnings("unchecked") - public ConfigElement parse(Element element) - { - LanguagesConfigElement configElement = null; - - if (element != null) - { - String name = element.getName(); - if (name.equals(LanguagesConfigElement.CONFIG_ELEMENT_ID) == false) - { - throw new ConfigException("LanguagesElementReader can only parse " + - LanguagesConfigElement.CONFIG_ELEMENT_ID + " elements, the element passed was '" + - name + "'"); - } - - configElement = new LanguagesConfigElement(); - - Iterator langsItr = element.elementIterator(ELEMENT_LANGUAGE); - while (langsItr.hasNext()) - { - Element language = langsItr.next(); - String localeCode = language.attributeValue(ATTRIBUTE_LOCALE); - String label = language.getTextTrim(); - - if (localeCode != null && localeCode.length() != 0 && - label != null && label.length() != 0) - { - // store the language code against the display label - configElement.addLanguage(localeCode, label); - } - } - } - - return configElement; - } -} diff --git a/war/src/main/java/org/alfresco/web/config/NavigationConfigElement.java b/war/src/main/java/org/alfresco/web/config/NavigationConfigElement.java deleted file mode 100644 index 95f61d044a..0000000000 --- a/war/src/main/java/org/alfresco/web/config/NavigationConfigElement.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.util.HashMap; -import java.util.List; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.element.ConfigElementAdapter; -import org.springframework.extensions.config.element.GenericConfigElement; - -/** - * Custom config element that represents the config data for navigation - * - * @author gavinc - */ -public class NavigationConfigElement extends ConfigElementAdapter -{ - private HashMap viewIds = new HashMap(); - private HashMap outcomes = new HashMap(); - - private boolean kidsPopulated = false; - - /** - * Default constructor - */ - public NavigationConfigElement() - { - super("navigation"); - } - - /** - * Constructor - * - * @param name Name of the element this config element represents - */ - public NavigationConfigElement(String name) - { - super(name); - } - - /** - * @see ConfigElement#getChildren() - */ - public List getChildren() - { - // lazily build the list of generic config elements representing - // the navigation overrides as the caller may not even call this method - - List kids = null; - - if (this.viewIds.size() > 0 || this.outcomes.size() > 0) - { - if (this.kidsPopulated == false) - { - // create generic config elements for the from-view-id items - for (String fromViewId : this.viewIds.keySet()) - { - GenericConfigElement ce = new GenericConfigElement(NavigationElementReader.ELEMENT_OVERRIDE); - ce.addAttribute(NavigationElementReader.ATTR_FROM_VIEWID, fromViewId); - - NavigationResult navRes = this.viewIds.get(fromViewId); - String result = navRes.getResult(); - if (navRes.isOutcome()) - { - ce.addAttribute(NavigationElementReader.ATTR_TO_OUTCOME, result); - } - else - { - ce.addAttribute(NavigationElementReader.ATTR_TO_VIEWID, result); - } - - // add the element - this.children.add(ce); - } - - // create generic config elements for the from-outcome items - for (String fromOutcome : this.outcomes.keySet()) - { - GenericConfigElement ce = new GenericConfigElement(NavigationElementReader.ELEMENT_OVERRIDE); - ce.addAttribute(NavigationElementReader.ATTR_FROM_OUTCOME, fromOutcome); - - NavigationResult navRes = this.outcomes.get(fromOutcome); - String result = navRes.getResult(); - if (navRes.isOutcome()) - { - ce.addAttribute(NavigationElementReader.ATTR_TO_OUTCOME, result); - } - else - { - ce.addAttribute(NavigationElementReader.ATTR_TO_VIEWID, result); - } - - // add the element - this.children.add(ce); - } - - this.kidsPopulated = true; - } - - kids = super.getChildren(); - } - - return kids; - } - - /** - * @see ConfigElement#combine(org.springframework.extensions.config.ConfigElement) - */ - public ConfigElement combine(ConfigElement configElement) - { - NavigationConfigElement newElement = (NavigationConfigElement)configElement; - NavigationConfigElement combinedElement = new NavigationConfigElement(); - - // add all the existing from view id overrides - for (String fromViewId : this.viewIds.keySet()) - { - combinedElement.addOverride(fromViewId, null, this.viewIds.get(fromViewId)); - } - - // add all the existing from outcome overrides - for (String fromOutcome : this.outcomes.keySet()) - { - combinedElement.addOverride(null, fromOutcome, this.outcomes.get(fromOutcome)); - } - - // add all the from view id overrides from the given element - HashMap viewIds = newElement.getViewIds(); - for (String fromViewId : viewIds.keySet()) - { - combinedElement.addOverride(fromViewId, null, viewIds.get(fromViewId)); - } - - // add all the from outcome overrides from the given element - HashMap outcomes = newElement.getOutcomes(); - for (String fromOutcome : outcomes.keySet()) - { - combinedElement.addOverride(null, fromOutcome, outcomes.get(fromOutcome)); - } - - return combinedElement; - } - - /** - * Returns the list of view ids that have overrides defined - * - * @return Map of view ids and navigation results - */ - public HashMap getViewIds() - { - return this.viewIds; - } - - /** - * Returns the list of outcomes that have overrides defined - * - * @return Map of outcomes and navigation results - */ - public HashMap getOutcomes() - { - return this.outcomes; - } - - /** - * Adds an override configuration item - * - * @param fromViewId The from-view-id value from the config - * @param fromOutcome The from-outcome value from the config - * @param toViewId The to-view-id value from the config - * @param toOutcome The to-outcome value from the config - */ - public void addOverride(String fromViewId, String fromOutcome, - String toViewId, String toOutcome) - { - // NOTE: the constructor will check the validity of the to* parameters - NavigationResult result = new NavigationResult(toViewId, toOutcome); - addOverride(fromViewId, fromOutcome, result); - } - - /** - * Adds an override configuration item - * - * @param fromViewId The from-view-id value from the config - * @param fromOutcome The from-outcome value from the config - * @param result The navigation result object to add - */ - public void addOverride(String fromViewId, String fromOutcome, - NavigationResult result) - { - if (fromViewId != null && fromOutcome != null) - { - throw new IllegalStateException("You can not have both a from-view-id and from-outcome"); - } - - if (fromViewId != null) - { - this.viewIds.put(fromViewId, result); - } - else if (fromOutcome != null) - { - this.outcomes.put(fromOutcome, result); - } - } - - /** - * Returns the best match navigation override configured for the given - * current view id and/or outcome. - * - * If an outcome is passed it takes precedence, the view id will not be - * used. - * - * @param fromViewId The current view id - * @param fromOutcome The current outcome - * @return The navigation result - */ - public NavigationResult getOverride(String fromViewId, String fromOutcome) - { - NavigationResult result = null; - - // look for a match for the outcome if one was provided - if (fromOutcome != null) - { - result = this.outcomes.get(fromOutcome); - } - else if (fromViewId != null) - { - result = this.viewIds.get(fromViewId); - } - - return result; - } -} diff --git a/war/src/main/java/org/alfresco/web/config/NavigationElementReader.java b/war/src/main/java/org/alfresco/web/config/NavigationElementReader.java deleted file mode 100644 index fc2f553bce..0000000000 --- a/war/src/main/java/org/alfresco/web/config/NavigationElementReader.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.util.Iterator; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.xml.elementreader.ConfigElementReader; -import org.dom4j.Element; - -/** - * Custom element reader to parse config for navigation overrides - * - * @author gavinc - */ -public class NavigationElementReader implements ConfigElementReader -{ - public static final String ELEMENT_NAVIGATION = "navigation"; - public static final String ELEMENT_OVERRIDE = "override"; - public static final String ATTR_FROM_VIEWID = "from-view-id"; - public static final String ATTR_FROM_OUTCOME = "from-outcome"; - public static final String ATTR_TO_VIEWID = "to-view-id"; - public static final String ATTR_TO_OUTCOME = "to-outcome"; - - /** - * @see org.springframework.extensions.config.xml.elementreader.ConfigElementReader#parse(org.dom4j.Element) - */ - public ConfigElement parse(Element element) - { - NavigationConfigElement configElement = null; - - if (element != null) - { - String name = element.getName(); - if (ELEMENT_NAVIGATION.equals(name) == false) - { - throw new ConfigException("NavigationElementReader can only parse " + - ELEMENT_NAVIGATION + "elements, " + "the element passed was '" + - name + "'"); - } - - configElement = new NavigationConfigElement(); - - // go through the items to show - Iterator items = element.elementIterator(); - while (items.hasNext()) - { - Element item = items.next(); - - // only process the override elements - if (ELEMENT_OVERRIDE.equals(item.getName())) - { - String fromViewId = item.attributeValue(ATTR_FROM_VIEWID); - String fromOutcome = item.attributeValue(ATTR_FROM_OUTCOME); - String toViewId = item.attributeValue(ATTR_TO_VIEWID); - String toOutcome = item.attributeValue(ATTR_TO_OUTCOME); - - configElement.addOverride(fromViewId, fromOutcome, toViewId, toOutcome); - } - } - } - - return configElement; - } -} diff --git a/war/src/main/java/org/alfresco/web/config/NavigationResult.java b/war/src/main/java/org/alfresco/web/config/NavigationResult.java deleted file mode 100644 index ffff40daf8..0000000000 --- a/war/src/main/java/org/alfresco/web/config/NavigationResult.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -/** - * Represents the result of a navigation config result. - * - * This object holds the string result which can either represent an outcome - * or a view id. - * - * @author gavinc - */ -public class NavigationResult -{ - private String result; - private boolean isOutcome = true; - - /** - * Default constructor - * - * @param viewId The to-view-id value - * @param outcome The to-outcome value - */ - public NavigationResult(String viewId, String outcome) - { - if (viewId != null && outcome != null) - { - throw new IllegalStateException("You can not have both a to-view-id and to-outcome"); - } - - if (outcome != null) - { - this.result = outcome; - } - else if (viewId != null) - { - this.result = viewId; - this.isOutcome = false; - } - } - - /** - * Returns the result - * - * @return The result - */ - public String getResult() - { - return this.result; - } - - /** - * Determines whether the result is an outcome - * - * @return true if the result represents an outcome, - * false if it represents a view id - */ - public boolean isOutcome() - { - return this.isOutcome; - } - - /** - * @see java.lang.Object#toString() - */ - public String toString() - { - StringBuilder buffer = new StringBuilder(super.toString()); - buffer.append(" (result=").append(this.result); - buffer.append(" isOutcome=").append(this.isOutcome).append(")"); - return buffer.toString(); - } -} diff --git a/war/src/main/java/org/alfresco/web/config/NodeTypeEvaluator.java b/war/src/main/java/org/alfresco/web/config/NodeTypeEvaluator.java deleted file mode 100644 index 8c16135d82..0000000000 --- a/war/src/main/java/org/alfresco/web/config/NodeTypeEvaluator.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import org.springframework.extensions.config.evaluator.Evaluator; -import org.alfresco.service.namespace.QName; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; - -/** - * Evaluator that determines whether a given object has a particular node type - * - * @author gavinc - */ -public class NodeTypeEvaluator implements Evaluator -{ - /** - * Determines whether the given node type matches the path of the given object - * - * @see org.springframework.extensions.config.evaluator.Evaluator#applies(java.lang.Object, java.lang.String) - */ - public boolean applies(Object obj, String condition) - { - boolean result = false; - - if (obj instanceof Node) - { - QName type = ((Node)obj).getType(); - if (type != null) - { - result = type.equals(Repository.resolveToQName(condition)); - } - } - - return result; - } - -} diff --git a/war/src/main/java/org/alfresco/web/config/PathEvaluator.java b/war/src/main/java/org/alfresco/web/config/PathEvaluator.java deleted file mode 100644 index afc8664d08..0000000000 --- a/war/src/main/java/org/alfresco/web/config/PathEvaluator.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import org.springframework.extensions.config.evaluator.Evaluator; -import org.alfresco.web.bean.repository.Node; - -/** - * Evaluator that determines whether a given object has a particular path - * - * @author gavinc - */ -public class PathEvaluator implements Evaluator -{ - /** - * Determines whether the given path matches the path of the given object - * - * @see org.springframework.extensions.config.evaluator.Evaluator#applies(java.lang.Object, java.lang.String) - */ - public boolean applies(Object obj, String condition) - { - boolean result = false; - - // TODO: Also deal with NodeRef object's being passed in - - if (obj instanceof Node) - { - String path = (String)((Node)obj).getPath(); - if (path != null) - { - result = path.equalsIgnoreCase(condition); - } - } - - return result; - } - -} diff --git a/war/src/main/java/org/alfresco/web/config/PropertySheetConfigElement.java b/war/src/main/java/org/alfresco/web/config/PropertySheetConfigElement.java deleted file mode 100644 index 66469018eb..0000000000 --- a/war/src/main/java/org/alfresco/web/config/PropertySheetConfigElement.java +++ /dev/null @@ -1,466 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.element.ConfigElementAdapter; - -/** - * Custom config element that represents the config data for a property sheet - * - * @author gavinc - */ -public class PropertySheetConfigElement extends ConfigElementAdapter -{ - public static final String CONFIG_ELEMENT_ID = "property-sheet"; - - protected Map items = new LinkedHashMap(8, 10f); - protected Map viewableItems = new LinkedHashMap(8, 10f); - protected Map editableItems = new LinkedHashMap(8, 10f); - - /** - * Default constructor - */ - public PropertySheetConfigElement() - { - super(CONFIG_ELEMENT_ID); - } - - /** - * Constructor - * - * @param name Name of the element this config element represents - */ - public PropertySheetConfigElement(String name) - { - super(name); - } - - /** - * @see ConfigElement#getChildren() - */ - public List getChildren() - { - throw new ConfigException("Reading the property-sheet config via the generic interfaces is not supported"); - } - - /** - * @see ConfigElement#combine(org.springframework.extensions.config.ConfigElement) - */ - public ConfigElement combine(ConfigElement configElement) - { - PropertySheetConfigElement combinedElement = new PropertySheetConfigElement(); - - // add all the existing properties - for (ItemConfig item : this.getItems().values()) - { - combinedElement.addItem(item); - } - - // add all the properties from the given element - for (ItemConfig item : ((PropertySheetConfigElement)configElement).getItems().values()) - { - combinedElement.addItem(item); - } - - return combinedElement; - } - - /** - * Adds an item to show - * - * @param itemConfig A pre-configured property or association config object - */ - /*package*/ void addItem(ItemConfig itemConfig) - { - this.items.put(itemConfig.getName(), itemConfig); - - if (itemConfig.isShownInViewMode()) - { - // add the item to the view list if it is editable - this.viewableItems.put(itemConfig.getName(), itemConfig); - } - else - { - // if the item was added previously as viewable it should be removed - if (viewableItems.containsKey(itemConfig.getName())) - { - this.viewableItems.remove(itemConfig.getName()); - } - } - - if (itemConfig.isShownInEditMode()) - { - // add the item to the edit list if it is editable - this.editableItems.put(itemConfig.getName(), itemConfig); - } - else - { - // if the item was added previously as editable it should be removed - if (editableItems.containsKey(itemConfig.getName())) - { - this.editableItems.remove(itemConfig.getName()); - } - } - } - - /** - * Adds a property to show - * - * @param name The name of the property - * @param displayLabel Display label to use for the property - * @param displayLabelId Display label message id to use for the property - * @param readOnly Sets whether the property should be rendered as read only - * @param converter The name of a converter to apply to the property control - * @param inView Sets whether the property should be shown when the property - * sheet is in view mode - * @param inEdit Sets whether the property should be shown when the property - * sheet is in edit mode - * @param compGenerator The name of a bean that can be used as a component generator - * @param ignoreIfMissing Sets whether the property should be rendered if it is not - * found in the data dictionary or the node itself - */ - /*package*/ void addProperty(String name, String displayLabel, String displayLabelId, String readOnly, - String converter, String inView, String inEdit, String compGenerator, - String ignoreIfMissing) - { - addItem(new PropertyConfig(name, displayLabel, displayLabelId, Boolean.parseBoolean(readOnly), - converter, inView, inEdit, compGenerator, ignoreIfMissing)); - } - - /** - * Adds an association to show - * - * @param name The name of the association - * @param displayLabel Display label to use for the property - * @param displayLabelId Display label message id to use for the property - * @param readOnly Sets whether the association should be rendered as read only - * @param converter The name of a converter to apply to the association control - * @param inView Sets whether the property should be shown when the property - * sheet is in view mode - * @param inEdit Sets whether the property should be shown when the property - * sheet is in edit mode - * @param compGenerator The name of a bean that can be used as a component generator - */ - /*package*/ void addAssociation(String name, String displayLabel, String displayLabelId, String readOnly, - String converter, String inView, String inEdit, String compGenerator) - { - addItem(new AssociationConfig(name, displayLabel, displayLabelId, Boolean.parseBoolean(readOnly), - converter, inView, inEdit, compGenerator)); - } - - /** - * Adds a child association to show - * - * @param name The name of the child association - * @param displayLabel Display label to use for the property - * @param displayLabelId Display label message id to use for the property - * @param readOnly Sets whether the association should be rendered as read only - * @param converter The name of a converter to apply to the association control - * @param inView Sets whether the property should be shown when the property - * sheet is in view mode - * @param inEdit Sets whether the property should be shown when the property - * sheet is in edit mode - * @param compGenerator The name of a bean that can be used as a component generator - */ - /*package*/ void addChildAssociation(String name, String displayLabel, String displayLabelId, String readOnly, - String converter, String inView, String inEdit, String compGenerator) - { - addItem(new ChildAssociationConfig(name, displayLabel, displayLabelId, Boolean.parseBoolean(readOnly), - converter, inView, inEdit, compGenerator)); - } - - /** - * Adds a separator - * - * @param name The name of the separator - * @param displayLabel Display label to use for the separator - * @param displayLabelId Display label message id to use for the separator - * @param inView Sets whether the separator should be shown when the property - * sheet is in view mode - * @param inEdit Sets whether the separator should be shown when the property - * sheet is in edit mode - * @param compGenerator The name of a bean that can be used as a component generator - */ - /*package*/ void addSeparator(String name, String displayLabel, String displayLabelId, - String inView, String inEdit, String compGenerator) - { - addItem(new SeparatorConfig(name, displayLabel, displayLabelId, inView, inEdit, compGenerator)); - } - - /** - * @return Returns a map of the all the items - */ - public Map getItems() - { - return this.items; - } - - /** - * @return Returns a list of item names to display - */ - public List getItemNamesToShow() - { - List propNames = new ArrayList(this.viewableItems.size()); - - for (String name : this.viewableItems.keySet()) - { - propNames.add(name); - } - - return propNames; - } - - /** - * @return Returns a map of the item names to show - */ - public Map getItemsToShow() - { - return this.viewableItems; - } - - /** - * @return Returns a list of item names to display - */ - public List getEditableItemNamesToShow() - { - List propNames = new ArrayList(this.editableItems.size()); - - for (String name : this.editableItems.keySet()) - { - propNames.add(name); - } - - return propNames; - } - - /** - * @return Returns a map of the item names to show - */ - public Map getEditableItemsToShow() - { - return this.editableItems; - } - - /** - * Inner class to represent a configured property sheet item - */ - public abstract class ItemConfig - { - private String name; - private String displayLabel; - private String displayLabelId; - private String converter; - private String componentGenerator; - private boolean readOnly; - private boolean showInViewMode = true; - private boolean showInEditMode = true; - private boolean ignoreIfMissing = true; - - public ItemConfig(String name, String displayLabel, String displayLabelId, - boolean readOnly, String converter, String inView, String inEdit, - String compGenerator, String ignoreIfMissing) - { - // check we have a name - if (name == null || name.length() == 0) - { - throw new ConfigException("You must specify a name for a proprty sheet item"); - } - - this.name = name; - this.displayLabel = displayLabel; - this.displayLabelId = displayLabelId; - this.readOnly = readOnly; - this.converter = converter; - this.componentGenerator = compGenerator; - - if (inView != null) - { - this.showInViewMode = Boolean.parseBoolean(inView); - } - if (inEdit != null) - { - this.showInEditMode = Boolean.parseBoolean(inEdit); - } - if (ignoreIfMissing != null) - { - this.ignoreIfMissing = Boolean.parseBoolean(ignoreIfMissing); - } - } - - /** - * @return The display label - */ - public String getDisplayLabel() - { - return this.displayLabel; - } - - /** - * @return The display label message id - */ - public String getDisplayLabelId() - { - return this.displayLabelId; - } - - /** - * @return The property name - */ - public String getName() - { - return this.name; - } - - /** - * @return Determines whether the property is configured as read only - */ - public boolean isReadOnly() - { - return this.readOnly; - } - - /** - * @return The converter id - */ - public String getConverter() - { - return this.converter; - } - - /** - * @return true if the property should be shown when the property sheet is in view mode - */ - public boolean isShownInViewMode() - { - return this.showInViewMode; - } - - /** - * @return true if the property should be shown when the property sheet is in edit mode - */ - public boolean isShownInEditMode() - { - return this.showInEditMode; - } - - /** - * @return The name of a bean that generates a component to represent this item - */ - public String getComponentGenerator() - { - return this.componentGenerator; - } - - /** - * @return Whether the property should be rendered if it is not found in the - * data dictionary or the node itself. - */ - public boolean getIgnoreIfMissing() - { - return this.ignoreIfMissing; - } - - /** - * @see java.lang.Object#toString() - */ - public String toString() - { - StringBuilder buffer = new StringBuilder(super.toString()); - buffer.append(" (name=").append(this.name); - buffer.append(" display-label=").append(this.displayLabel); - buffer.append(" display-label-id=").append(this.displayLabelId); - buffer.append(" converter=").append(this.converter); - buffer.append(" read-only=").append(this.readOnly); - buffer.append(" show-in-view-mode=").append(this.showInViewMode); - buffer.append(" show-in-edit-mode=").append(this.showInEditMode); - buffer.append(" ignore-if-missing=").append(this.ignoreIfMissing); - buffer.append(" component-generator=").append(this.componentGenerator).append(")"); - return buffer.toString(); - } - } - - /** - * Inner class to represent a configured property - */ - public class PropertyConfig extends ItemConfig - { - public PropertyConfig(String name, String displayLabel, String displayLabelId, - boolean readOnly, String converter, String inView, String inEdit, - String compGenerator, String ignoreIfMissing) - { - super(name, displayLabel, displayLabelId, readOnly, converter, - inView, inEdit, compGenerator, ignoreIfMissing); - } - } - - /** - * Inner class to represent a configured association - */ - public class AssociationConfig extends ItemConfig - { - public AssociationConfig(String name, String displayLabel, String displayLabelId, - boolean readOnly, String converter, String inView, String inEdit, - String compGenerator) - { - super(name, displayLabel, displayLabelId, readOnly, converter, - inView, inEdit, compGenerator, null); - } - } - - /** - * Inner class to represent a configured child association - */ - public class ChildAssociationConfig extends ItemConfig - { - public ChildAssociationConfig(String name, String displayLabel, String displayLabelId, - boolean readOnly, String converter, String inView, String inEdit, - String compGenerator) - { - super(name, displayLabel, displayLabelId, readOnly, converter, - inView, inEdit, compGenerator, null); - } - } - - /** - * Inner class to represent a configured separator - */ - public class SeparatorConfig extends ItemConfig - { - public SeparatorConfig(String name, String displayLabel, String displayLabelId, - String inView, String inEdit, String compGenerator) - { - super(name, displayLabel, displayLabelId, false, null, - inView, inEdit, compGenerator, null); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/config/PropertySheetElementReader.java b/war/src/main/java/org/alfresco/web/config/PropertySheetElementReader.java deleted file mode 100644 index 4cb13923c9..0000000000 --- a/war/src/main/java/org/alfresco/web/config/PropertySheetElementReader.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.util.Iterator; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.xml.elementreader.ConfigElementReader; -import org.dom4j.Element; - -/** - * Custom element reader to parse config for property sheets - * - * @author gavinc - */ -public class PropertySheetElementReader implements ConfigElementReader -{ - public static final String ELEMENT_PROPERTY_SHEET = "property-sheet"; - public static final String ELEMENT_SHOW_PROPERTY = "show-property"; - public static final String ELEMENT_SHOW_ASSOC = "show-association"; - public static final String ELEMENT_SHOW_CHILD_ASSOC = "show-child-association"; - public static final String ELEMENT_SEPARATOR = "separator"; - public static final String ATTR_NAME = "name"; - public static final String ATTR_DISPLAY_LABEL = "display-label"; - public static final String ATTR_DISPLAY_LABEL_ID = "display-label-id"; - public static final String ATTR_READ_ONLY = "read-only"; - public static final String ATTR_CONVERTER = "converter"; - public static final String ATTR_SHOW_IN_EDIT_MODE = "show-in-edit-mode"; - public static final String ATTR_SHOW_IN_VIEW_MODE = "show-in-view-mode"; - public static final String ATTR_COMPONENT_GENERATOR = "component-generator"; - public static final String ATTR_IGNORE_IF_MISSING = "ignore-if-missing"; - - /** - * @see org.springframework.extensions.config.xml.elementreader.ConfigElementReader#parse(org.dom4j.Element) - */ - @SuppressWarnings("unchecked") - public ConfigElement parse(Element element) - { - PropertySheetConfigElement configElement = null; - - if (element != null) - { - String name = element.getName(); - if (name.equals(ELEMENT_PROPERTY_SHEET) == false) - { - throw new ConfigException("PropertySheetElementReader can only parse " + - ELEMENT_PROPERTY_SHEET + "elements, " + "the element passed was '" + - name + "'"); - } - - configElement = new PropertySheetConfigElement(); - - // go through the items to show - Iterator items = element.elementIterator(); - while (items.hasNext()) - { - Element item = items.next(); - String propName = item.attributeValue(ATTR_NAME); - String label = item.attributeValue(ATTR_DISPLAY_LABEL); - String labelId = item.attributeValue(ATTR_DISPLAY_LABEL_ID); - String readOnly = item.attributeValue(ATTR_READ_ONLY); - String converter = item.attributeValue(ATTR_CONVERTER); - String inEdit = item.attributeValue(ATTR_SHOW_IN_EDIT_MODE); - String inView = item.attributeValue(ATTR_SHOW_IN_VIEW_MODE); - String compGenerator = item.attributeValue(ATTR_COMPONENT_GENERATOR); - - if (ELEMENT_SHOW_PROPERTY.equals(item.getName())) - { - String ignoreIfMissing = item.attributeValue(ATTR_IGNORE_IF_MISSING); - - // add the property to show to the custom config element - configElement.addProperty(propName, label, labelId, readOnly, converter, - inView, inEdit, compGenerator, ignoreIfMissing); - } - else if (ELEMENT_SHOW_ASSOC.equals(item.getName())) - { - configElement.addAssociation(propName, label, labelId, readOnly, converter, - inView, inEdit, compGenerator); - } - else if (ELEMENT_SHOW_CHILD_ASSOC.equals(item.getName())) - { - configElement.addChildAssociation(propName, label, labelId, readOnly, converter, - inView, inEdit, compGenerator); - } - else if (ELEMENT_SEPARATOR.equals(item.getName())) - { - configElement.addSeparator(propName, label, labelId, inView, inEdit, compGenerator); - } - } - } - - return configElement; - } - -} diff --git a/war/src/main/java/org/alfresco/web/config/SidebarConfigElement.java b/war/src/main/java/org/alfresco/web/config/SidebarConfigElement.java deleted file mode 100644 index c7cf273750..0000000000 --- a/war/src/main/java/org/alfresco/web/config/SidebarConfigElement.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.io.Serializable; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.element.ConfigElementAdapter; -import org.springframework.extensions.surf.util.ParameterCheck; - -/** - * Custom config element that represents the config data for the sidebar - * - * @author gavinc - */ -public class SidebarConfigElement extends ConfigElementAdapter implements Serializable -{ - private static final long serialVersionUID = -251308123183340915L; - - public static final String CONFIG_ELEMENT_ID = "sidebar"; - - private String defaultPlugin; - private Map plugins = new LinkedHashMap(8, 10f); - - /** - * Default constructor - */ - public SidebarConfigElement() - { - super(CONFIG_ELEMENT_ID); - } - - /** - * Constructor - * - * @param name Name of the element this config element represents - */ - public SidebarConfigElement(String name) - { - super(name); - } - - /** - * @see ConfigElement#getChildren() - */ - public List getChildren() - { - throw new ConfigException("Reading the sidebar config via the generic interfaces is not supported"); - } - - /** - * @see ConfigElement#combine(org.springframework.extensions.config.ConfigElement) - */ - public ConfigElement combine(ConfigElement configElement) - { - SidebarConfigElement newElement = (SidebarConfigElement)configElement; - SidebarConfigElement combinedElement = new SidebarConfigElement(); - - // add all the plugins from this element - for (SidebarPluginConfig plugin : this.getPlugins().values()) - { - combinedElement.addPlugin(plugin); - } - - // add all the plugins from the given element - for (SidebarPluginConfig plugin : newElement.getPlugins().values()) - { - combinedElement.addPlugin(plugin); - } - - // work out the default plugin - String newDefaultPlugin = newElement.getDefaultPlugin(); - if (newDefaultPlugin != null) - { - combinedElement.setDefaultPlugin(newDefaultPlugin); - } - else - { - combinedElement.setDefaultPlugin(this.getDefaultPlugin()); - } - - return combinedElement; - } - - /** - * Returns the named plugin - * - * @param id The id of the plugin to retrieve - * @return The SidebarPluginConfig object for the requested plugin or null if it doesn't exist - */ - public SidebarPluginConfig getPlugin(String id) - { - return this.plugins.get(id); - } - - /** - * @return Returns a map of the plugins. A linked hash map is used internally to - * preserve ordering. - */ - public Map getPlugins() - { - return this.plugins; - } - - /** - * @return The id of the default plugin, null if there isn't a default defined - */ - public String getDefaultPlugin() - { - return this.defaultPlugin; - } - - /** - * Sets the plugin to use as the default - * - * @param defaultPlugin Id of the default plugin - */ - public void setDefaultPlugin(String defaultPlugin) - { - this.defaultPlugin = defaultPlugin; - } - - /** - * Adds a plugin - * - * @param pluginConfig A pre-configured plugin config object - */ - /*package*/ void addPlugin(SidebarPluginConfig pluginConfig) - { - this.plugins.put(pluginConfig.getId(), pluginConfig); - } - - /** - * Inner class representing the configuration of a sidebar plugin - * - * @author gavinc - */ - public static class SidebarPluginConfig implements Serializable - { - private static final long serialVersionUID = 1400852211128756652L; - - protected String id; - protected String page; - protected String actionsConfigId; - protected String icon; - protected String label; - protected String labelId; - protected String description; - protected String descriptionId; - - public SidebarPluginConfig(String id, String page, - String label, String labelId, - String description, String descriptionId, - String actionsConfigId, String icon) - { - // check the mandatory parameters are present - ParameterCheck.mandatoryString("id", id); - ParameterCheck.mandatoryString("page", page); - - this.id = id; - this.page = page; - this.icon = icon; - this.label = label; - this.labelId = labelId; - this.description = description; - this.descriptionId = descriptionId; - this.actionsConfigId = actionsConfigId; - } - - public String getId() - { - return this.id; - } - - public String getPage() - { - return this.page; - } - - public String getIcon() - { - return this.icon; - } - - public String getlabel() - { - return this.label; - } - - public String getlabelId() - { - return this.labelId; - } - - public String getDescription() - { - return this.description; - } - - public String getDescriptionId() - { - return this.descriptionId; - } - - public String getActionsConfigId() - { - return this.actionsConfigId; - } - - /** - * @see java.lang.Object#toString() - */ - @Override - public String toString() - { - StringBuilder buffer = new StringBuilder(super.toString()); - buffer.append(" (id=").append(this.id); - buffer.append(" page=").append(this.page); - buffer.append(" icon=").append(this.icon); - buffer.append(" label=").append(this.label); - buffer.append(" labelId=").append(this.labelId); - buffer.append(" description=").append(this.description); - buffer.append(" descriptionId=").append(this.descriptionId); - buffer.append(" actions-config-id=").append(this.actionsConfigId).append(")"); - return buffer.toString(); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/config/SidebarElementReader.java b/war/src/main/java/org/alfresco/web/config/SidebarElementReader.java deleted file mode 100644 index f3f8a50d5d..0000000000 --- a/war/src/main/java/org/alfresco/web/config/SidebarElementReader.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.util.Iterator; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.xml.elementreader.ConfigElementReader; -import org.dom4j.Element; - -/** - * Custom element reader to parse config for the sidebar - * - * @author gavinc - */ -public class SidebarElementReader implements ConfigElementReader -{ - public static final String ELEMENT_SIDEBAR = "sidebar"; - public static final String ELEMENT_PLUGINS = "plugins"; - public static final String ELEMENT_PLUGIN = "plugin"; - public static final String ELEMENT_DEFAULT_PLUGIN = "default-plugin"; - public static final String ATTR_ID = "id"; - public static final String ATTR_LABEL = "label"; - public static final String ATTR_LABEL_ID = "label-id"; - public static final String ATTR_DESCRIPTION = "description"; - public static final String ATTR_DESCRIPTION_ID = "description-id"; - public static final String ATTR_PAGE = "page"; - public static final String ATTR_ICON = "icon"; - public static final String ATTR_ACTIONS_CONFIG_ID = "actions-config-id"; - - /** - * @see org.springframework.extensions.config.xml.elementreader.ConfigElementReader#parse(org.dom4j.Element) - */ - @SuppressWarnings("unchecked") - public ConfigElement parse(Element element) - { - SidebarConfigElement configElement = null; - - if (element != null) - { - String elementName = element.getName(); - if (elementName.equals(ELEMENT_SIDEBAR) == false) - { - throw new ConfigException("SidebarElementReader can only parse " + - ELEMENT_SIDEBAR + "elements, the element passed was '" + - elementName + "'"); - } - - configElement = new SidebarConfigElement(); - - // go through the plugins that make up the sidebar - Element pluginsElem = element.element(ELEMENT_PLUGINS); - if (pluginsElem != null) - { - Iterator plugins = pluginsElem.elementIterator(ELEMENT_PLUGIN); - while (plugins.hasNext()) - { - Element plugin = plugins.next(); - - String id = plugin.attributeValue(ATTR_ID); - String page = plugin.attributeValue(ATTR_PAGE); - String label = plugin.attributeValue(ATTR_LABEL); - String labelId = plugin.attributeValue(ATTR_LABEL_ID); - String description = plugin.attributeValue(ATTR_DESCRIPTION); - String descriptionId = plugin.attributeValue(ATTR_DESCRIPTION_ID); - String actionsConfigId = plugin.attributeValue(ATTR_ACTIONS_CONFIG_ID); - String icon = plugin.attributeValue(ATTR_ICON); - - SidebarConfigElement.SidebarPluginConfig cfg = - new SidebarConfigElement.SidebarPluginConfig(id, page, - label, labelId, description, descriptionId, - actionsConfigId, icon); - - configElement.addPlugin(cfg); - } - } - - // see if a default plugin is specified - Element defaultPlugin = element.element(ELEMENT_DEFAULT_PLUGIN); - if (defaultPlugin != null) - { - configElement.setDefaultPlugin(defaultPlugin.getTextTrim()); - } - } - - return configElement; - } -} diff --git a/war/src/main/java/org/alfresco/web/config/ViewsConfigElement.java b/war/src/main/java/org/alfresco/web/config/ViewsConfigElement.java deleted file mode 100644 index 410ed278a9..0000000000 --- a/war/src/main/java/org/alfresco/web/config/ViewsConfigElement.java +++ /dev/null @@ -1,378 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.element.ConfigElementAdapter; - -/** - * Custom config element that represents config values for views in the client - * - * @author Gavin Cornwell - */ -public class ViewsConfigElement extends ConfigElementAdapter implements Serializable -{ - private static final long serialVersionUID = -503735723795178986L; - - public static final String CONFIG_ELEMENT_ID = "views"; - - public static final String VIEW_DETAILS = "details"; - public static final String VIEW_ICONS = "icons"; - public static final String VIEW_LIST = "list"; - public static final String VIEW_BUBBLE = "bubble"; - public static final String SORT_ASCENDING = "ascending"; - public static final String SORT_DESCENDING = "descending"; - - private static final String SEPARATOR = ":"; - - // defaults - private int defaultPageSize = 10; - private String defaultView = "details"; - private String defaultSortColumn = "name"; - - // list to store all the configured views - private List views = new ArrayList(4); - - // map to store all the default views - private Map defaultViews = new HashMap(4); - - // map to store all default page sizes for configured client views - private Map pageSizes = new HashMap(10); - - // map to store default sort columns for configured views - private Map sortColumns = new HashMap(4); - - // list of pages that have been configured to have ascending sorts - private Map sortDirections = new HashMap(1); - - /** - * Default Constructor - */ - public ViewsConfigElement() - { - super(CONFIG_ELEMENT_ID); - - // add the default page sizes to the map - this.pageSizes.put(VIEW_DETAILS, defaultPageSize); - this.pageSizes.put(VIEW_LIST, defaultPageSize); - this.pageSizes.put(VIEW_ICONS, 9); - this.pageSizes.put(VIEW_BUBBLE, 5); - } - - /** - * Constructor - * - * @param name Name of the element this config element represents - */ - public ViewsConfigElement(String name) - { - super(name); - } - - /** - * @see org.springframework.extensions.config.element.ConfigElementAdapter#getChildren() - */ - @Override - public List getChildren() - { - throw new ConfigException("Reading the views config via the generic interfaces is not supported"); - } - - /** - * @see org.springframework.extensions.config.element.ConfigElementAdapter#combine(org.springframework.extensions.config.ConfigElement) - */ - public ConfigElement combine(ConfigElement configElement) - { - ViewsConfigElement newElement = (ViewsConfigElement)configElement; - ViewsConfigElement combinedElement = new ViewsConfigElement(); - - // copy all the config from this element into the new one - for (String viewImpl : this.views) - { - combinedElement.addView(viewImpl); - } - - for (String page : this.defaultViews.keySet()) - { - combinedElement.addDefaultView(page, this.defaultViews.get(page)); - } - - for (String pageView : this.pageSizes.keySet()) - { - if (pageView.indexOf(SEPARATOR) != -1) - { - String page = pageView.substring(0, pageView.indexOf(SEPARATOR)); - String view = pageView.substring(pageView.indexOf(SEPARATOR)+1); - combinedElement.addDefaultPageSize(page, view, this.pageSizes.get(pageView).intValue()); - } - } - - for (String page : this.sortColumns.keySet()) - { - combinedElement.addDefaultSortColumn(page, this.sortColumns.get(page)); - } - - for (String page : this.sortDirections.keySet()) - { - combinedElement.addSortDirection(page, this.sortDirections.get(page)); - } - - // copy all the config from the element to be combined into the new one - for (String viewImpl : newElement.getViews()) - { - combinedElement.addView(viewImpl); - } - - Map newDefaultViews = newElement.getDefaultViews(); - for (String page : newDefaultViews.keySet()) - { - combinedElement.addDefaultView(page, newDefaultViews.get(page)); - } - - Map newPageSizes = newElement.getDefaultPageSizes(); - for (String pageView : newPageSizes.keySet()) - { - if (pageView.indexOf(SEPARATOR) != -1) - { - String page = pageView.substring(0, pageView.indexOf(SEPARATOR)); - String view = pageView.substring(pageView.indexOf(SEPARATOR)+1); - combinedElement.addDefaultPageSize(page, view, newPageSizes.get(pageView).intValue()); - } - } - - Map newSortColumns = newElement.getDefaultSortColumns(); - for (String page : newSortColumns.keySet()) - { - combinedElement.addDefaultSortColumn(page, newSortColumns.get(page)); - } - - Map existingSortDirs = newElement.getSortDirections(); - for (String page : existingSortDirs.keySet()) - { - combinedElement.addSortDirection(page, existingSortDirs.get(page)); - } - - return combinedElement; - } - - /** - * Adds a configured view - * - * @param renderer The implementation class of the view (the renderer) - */ - /*package*/ void addView(String renderer) - { - this.views.add(renderer); - } - - /** - * Returns a map of configured views for the client - * - * @return List of the implementation classes for the configured views - */ - public List getViews() - { - return this.views; - } - - /** - * Adds a default view setting - * - * @param page The page to set the default view for - * @param view The view name that will be the default - */ - /*package*/ void addDefaultView(String page, String view) - { - this.defaultViews.put(page, view); - } - - /** - * Returns the default view for the given page - * - * @param page The page to get the default view for - * @return The defualt view, if there isn't a configured default for the - * given page 'details' will be returned - */ - public String getDefaultView(String page) - { - String view = this.defaultViews.get(page); - - if (view == null) - { - view = this.defaultView; - } - - return view; - } - - /** - * Returns a map of default views for each page - * - * @return Map of default views - */ - /*package*/ Map getDefaultViews() - { - return this.defaultViews; - } - - /** - * Adds a configured page size to the internal store - * - * @param page The name of the page i.e. browse, forums etc. - * @param view The name of the view the size is for i.e. details, icons etc. - * @param size The size of the page - */ - /*package*/ void addDefaultPageSize(String page, String view, int size) - { - this.pageSizes.put(page + SEPARATOR + view, new Integer(size)); - } - - /** - * Returns the page size for the given page and view combination - * - * @param page The name of the page i.e. browse, forums etc. - * @param view The name of the view the size is for i.e. details, icons etc. - * @return The size of the requested page, if the combination doesn't exist - * the default for the view will be used, if the view doesn't exist either - * 10 will be returned. - */ - public int getDefaultPageSize(String page, String view) - { - Integer pageSize = this.pageSizes.get(page + SEPARATOR + view); - - // try just the view if the combination isn't present - if (pageSize == null) - { - pageSize = this.pageSizes.get(view); - - // if the view is not present either default to 10 - if (pageSize == null) - { - pageSize = new Integer(10); - } - } - - return pageSize.intValue(); - } - - /** - * Returns a map of page sizes - * - * @return Map of page sizes - */ - /*package*/ Map getDefaultPageSizes() - { - return this.pageSizes; - } - - /** - * Adds a default sorting column for the given page - * - * @param page The name of the page i.e. browse, forums etc. - * @param column The name of the column to initially sort by - */ - /*package*/ void addDefaultSortColumn(String page, String column) - { - this.sortColumns.put(page, column); - } - - /** - * Returns the default sort column for the given page - * - * @param page The name of the page i.e. browse, forums etc. - * @return The name of the column to sort by, name is returned if - * the page is not found - */ - public String getDefaultSortColumn(String page) - { - String column = this.sortColumns.get(page); - - if (column == null) - { - column = this.defaultSortColumn; - } - - return column; - } - - /** - * Returns a map of the sorted columns for each page - * - * @return Map of sort columns - */ - /*package*/ Map getDefaultSortColumns() - { - return this.sortColumns; - } - - /** - * Sets the given page as using the given sort direction - * - * @param page The name of the page i.e. browse, forums etc. - * @param dir The sort direction - */ - /*package*/ void addSortDirection(String page, String dir) - { - this.sortDirections.put(page, dir); - } - - /** - * Determines whether the given page has been - * configured to use descending sorting by default - * - * @param page The name of the page i.e. browse, forums etc. - * @return true if the page should use descending sorts - */ - public boolean hasDescendingSort(String page) - { - boolean usesDescendingSort = false; - - String sortDir = this.sortDirections.get(page); - if (sortDir != null && sortDir.equalsIgnoreCase(SORT_DESCENDING)) - { - usesDescendingSort = true; - } - - return usesDescendingSort; - } - - /** - * Returns a map of the sort directions - * - * @return Map of sort directions - */ - /*package*/ Map getSortDirections() - { - return this.sortDirections; - } -} diff --git a/war/src/main/java/org/alfresco/web/config/ViewsElementReader.java b/war/src/main/java/org/alfresco/web/config/ViewsElementReader.java deleted file mode 100644 index e084be4819..0000000000 --- a/war/src/main/java/org/alfresco/web/config/ViewsElementReader.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.util.Iterator; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.xml.elementreader.ConfigElementReader; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.dom4j.Element; - -/** - * Custom element reader to parse config for client views - * - * @author Gavin Cornwell - */ -public class ViewsElementReader implements ConfigElementReader -{ - public static final String ELEMENT_VIEW = "view"; - public static final String ELEMENT_VIEWIMPL = "view-impl"; - public static final String ELEMENT_VIEWDEFAULTS = "view-defaults"; - public static final String ELEMENT_PAGESIZE = "page-size"; - public static final String ELEMENT_SORTCOLUMN = "sort-column"; - public static final String ELEMENT_SORTDIRECTION = "sort-direction"; - - private static Log logger = LogFactory.getLog(ViewsElementReader.class); - - /** - * @see org.springframework.extensions.config.xml.elementreader.ConfigElementReader#parse(org.dom4j.Element) - */ - @SuppressWarnings("unchecked") - public ConfigElement parse(Element element) - { - ViewsConfigElement configElement = null; - - if (element != null) - { - String name = element.getName(); - if (name.equals(ViewsConfigElement.CONFIG_ELEMENT_ID) == false) - { - throw new ConfigException("ViewsElementReader can only parse " + - ViewsConfigElement.CONFIG_ELEMENT_ID + " elements, the element passed was '" + - name + "'"); - } - - configElement = new ViewsConfigElement(); - - // get the configured views - Iterator renderers = element.elementIterator(ELEMENT_VIEWIMPL); - while (renderers.hasNext()) - { - Element renderer = renderers.next(); - configElement.addView(renderer.getTextTrim()); - } - - // get all the view related default settings - Element viewDefaults = element.element(ELEMENT_VIEWDEFAULTS); - if (viewDefaults != null) - { - Iterator pages = viewDefaults.elementIterator(); - while (pages.hasNext()) - { - Element page = pages.next(); - String pageName = page.getName(); - - // get the default view mode for the page - Element defaultView = page.element(ELEMENT_VIEW); - if (defaultView != null) - { - String viewName = defaultView.getTextTrim(); - configElement.addDefaultView(pageName, viewName); - } - - // get the initial sort column - Element sortColumn = page.element(ELEMENT_SORTCOLUMN); - if (sortColumn != null) - { - String column = sortColumn.getTextTrim(); - configElement.addDefaultSortColumn(pageName, column); - } - - // get the sort direction option - Element sortDir = page.element(ELEMENT_SORTDIRECTION); - if (sortDir != null) - { - configElement.addSortDirection(pageName, sortDir.getTextTrim()); - } - - // process the page-size element - processPageSizeElement(page.element(ELEMENT_PAGESIZE), - pageName, configElement); - } - } - } - - return configElement; - } - - /** - * Processes a page-size element - * - * @param pageSizeElement The element to process - * @param page The page the page-size element belongs to - * @param configElement The config element being populated - */ - @SuppressWarnings("unchecked") - private void processPageSizeElement(Element pageSizeElement, String page, - ViewsConfigElement configElement) - { - if (pageSizeElement != null) - { - Iterator views = pageSizeElement.elementIterator(); - while (views.hasNext()) - { - Element view = views.next(); - String viewName = view.getName(); - String pageSize = view.getTextTrim(); - try - { - configElement.addDefaultPageSize(page, viewName, Integer.parseInt(pageSize)); - } - catch (NumberFormatException nfe) - { - if (logger.isWarnEnabled()) - { - logger.warn("Failed to set page size for view '" + viewName + - "' in page '" + page + "' as '" + pageSize + - "' is an invalid number!"); - } - } - } - } - } -} diff --git a/war/src/main/java/org/alfresco/web/config/WebClientConfigBootstrap.java b/war/src/main/java/org/alfresco/web/config/WebClientConfigBootstrap.java deleted file mode 100644 index b7b71163c1..0000000000 --- a/war/src/main/java/org/alfresco/web/config/WebClientConfigBootstrap.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.util.List; - -import org.springframework.extensions.config.ConfigDeployer; -import org.springframework.extensions.config.ConfigDeployment; -import org.springframework.extensions.config.ConfigService; -import org.springframework.extensions.config.source.UrlConfigSource; -import org.alfresco.error.AlfrescoRuntimeException; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.BeanNameAware; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; - - -/** - * Web client config bootstrap - * - * @author Roy Wetherall - */ -public class WebClientConfigBootstrap implements ApplicationContextAware, BeanNameAware, ConfigDeployer -{ - - /** The bean name. */ - private String beanName; - - /** The application context */ - private ApplicationContext applicationContext; - - /** Dependency */ - private ConfigService configService; - - /** List of configs */ - private List configs; - - /** - * Set the configs - * - * @param configs the configs - */ - public void setConfigs(List configs) - { - this.configs = configs; - } - - /** - * - * @deprecated - */ - public void init() - { - // TODO - see JIRA Task AR-1715 - refactor calling modules to inject webClientConfigService, and use init-method="register" directly - // (instead of init-method="init"). Can then remove applicationContext and no longer implement ApplicationContextAware - - if (this.applicationContext.containsBean("webClientConfigService") == true) - { - ConfigService configService = (ConfigService)this.applicationContext.getBean("webClientConfigService"); - if (configService != null) - { - setConfigService(configService); - register(); - } - } - } - - - /* (non-Javadoc) - * @see org.springframework.beans.factory.BeanNameAware#setBeanName(java.lang.String) - */ - public void setBeanName(String name) - { - this.beanName = name; - } - - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException - { - this.applicationContext = applicationContext; - } - - public void setConfigService(ConfigService configService) - { - this.configService = configService; - } - - /* (non-Javadoc) - * @see org.alfresco.config.ConfigDeployer#getSortKey() - */ - public String getSortKey() - { - return this.beanName; - } - - public void register() - { - if (configService == null) - { - throw new AlfrescoRuntimeException("Config service must be provided"); - } - - configService.addDeployer(this); - } - - /** - * Initialisation method - */ - public List initConfig() - { - if (configService != null && this.configs != null && this.configs.size() != 0) - { - UrlConfigSource configSource = new UrlConfigSource(this.configs, true); - return configService.appendConfig(configSource); - } - - return null; - } - -} diff --git a/war/src/main/java/org/alfresco/web/config/WizardsConfigElement.java b/war/src/main/java/org/alfresco/web/config/WizardsConfigElement.java deleted file mode 100644 index 765e222c2d..0000000000 --- a/war/src/main/java/org/alfresco/web/config/WizardsConfigElement.java +++ /dev/null @@ -1,483 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.element.ConfigElementAdapter; -import org.springframework.extensions.surf.util.ParameterCheck; - -/** - * Custom config element that represents the config data for a property sheet - * - * @author gavinc - */ -public class WizardsConfigElement extends ConfigElementAdapter -{ - public static final String CONFIG_ELEMENT_ID = "wizards"; - - private Map wizards = new LinkedHashMap(8, 10f); - - /** - * Default constructor - */ - public WizardsConfigElement() - { - super(CONFIG_ELEMENT_ID); - } - - /** - * Constructor - * - * @param name Name of the element this config element represents - */ - public WizardsConfigElement(String name) - { - super(name); - } - - /** - * @see ConfigElement#getChildren() - */ - public List getChildren() - { - throw new ConfigException("Reading the wizards config via the generic interfaces is not supported"); - } - - /** - * @see ConfigElement#combine(org.springframework.extensions.config.ConfigElement) - */ - public ConfigElement combine(ConfigElement configElement) - { - WizardsConfigElement combined = new WizardsConfigElement(); - - // add all the wizards from this element - for (WizardConfig wizard : this.getWizards().values()) - { - combined.addWizard(wizard); - } - - // add all the wizards from the given element - for (WizardConfig wizard : ((WizardsConfigElement)configElement).getWizards().values()) - { - combined.addWizard(wizard); - } - - return combined; - } - - /** - * Returns the named wizard - * - * @param name The name of the wizard to retrieve - * @return The WizardConfig object for the requested wizard or null if it doesn't exist - */ - public WizardConfig getWizard(String name) - { - return this.wizards.get(name); - } - - /** - * @return Returns a map of the wizards - */ - public Map getWizards() - { - return this.wizards; - } - - /** - * Adds a wizard - * - * @param wizardConfig A pre-configured wizard config object - */ - /*package*/ void addWizard(WizardConfig wizardConfig) - { - this.wizards.put(wizardConfig.getName(), wizardConfig); - } - - public abstract static class AbstractConfig implements Serializable - { - protected String title; - protected String titleId; - protected String description; - protected String descriptionId; - - - - protected AbstractConfig() - { - super(); - } - - public AbstractConfig(String title, String titleId, - String description, String descriptionId) - { - this.title = title; - this.titleId = titleId; - this.description = description; - this.descriptionId = descriptionId; - } - - public String getDescription() - { - return this.description; - } - - public String getDescriptionId() - { - return this.descriptionId; - } - - public String getTitle() - { - return this.title; - } - - public String getTitleId() - { - return this.titleId; - } - } - - /** - * Represents the configuration of a single wizard i.e. the <wizard> element - */ - public static class WizardConfig extends AbstractConfig implements Serializable - { - private static final long serialVersionUID = -3377339374041580932L; - - protected String subTitle; - protected String subTitleId; - protected String name; - protected String managedBean; - protected String icon; - protected String errorMsgId = "error_wizard"; - - protected Map steps = new LinkedHashMap(4); - - protected WizardConfig() - { - super(); - } - - public WizardConfig(String name, String bean, String icon, - String title, String titleId, - String subTitle, String subTitleId, - String description, String descriptionId, - String errorMsgId) - { - super(title, titleId, description, descriptionId); - - // check we have a name - ParameterCheck.mandatoryString("name", name); - - this.subTitle = subTitle; - this.subTitleId = subTitleId; - this.name = name; - this.managedBean = bean; - this.icon = icon; - - if (errorMsgId != null && errorMsgId.length() > 0) - { - this.errorMsgId = errorMsgId; - } - } - - public String getName() - { - return this.name; - } - - public String getManagedBean() - { - return this.managedBean; - } - - public String getSubTitle() - { - return this.subTitle; - } - - public String getSubTitleId() - { - return this.subTitleId; - } - - public String getIcon() - { - return this.icon; - } - - public String getErrorMessageId() - { - return this.errorMsgId; - } - - public int getNumberSteps() - { - return this.steps.size(); - } - - public Map getSteps() - { - return this.steps; - } - - public List getStepsAsList() - { - List stepList = new ArrayList(this.steps.size()); - - for (StepConfig stepCfg : this.steps.values()) - { - stepList.add(stepCfg); - } - - return stepList; - } - - public StepConfig getStepByName(String name) - { - return this.steps.get(name); - } - - /*package*/ void addStep(StepConfig step) - { - this.steps.put(step.getName(), step); - } - - /** - * @see java.lang.Object#toString() - */ - @Override - public String toString() - { - StringBuilder buffer = new StringBuilder(super.toString()); - buffer.append(" (name=").append(this.name); - buffer.append(" managed-bean=").append(this.managedBean); - buffer.append(" icon=").append(this.icon); - buffer.append(" title=").append(this.title); - buffer.append(" titleId=").append(this.titleId); - buffer.append(" subTitle=").append(this.subTitle); - buffer.append(" subTitleId=").append(this.subTitleId); - buffer.append(" description=").append(this.description); - buffer.append(" descriptionId=").append(this.descriptionId); - buffer.append(" errorMsgId=").append(this.errorMsgId).append(")"); - return buffer.toString(); - } - } - - /** - * Represents the configuration of a page in a wizard i.e. the <page> element - */ - public static class PageConfig extends AbstractConfig implements Serializable - { - private static final long serialVersionUID = 4154515148190230391L; - - protected String path; - protected String instruction; - protected String instructionId; - - public PageConfig(String path, - String title, String titleId, - String description, String descriptionId, - String instruction, String instructionId) - { - super(title, titleId, description, descriptionId); - - // check we have a path - ParameterCheck.mandatoryString("path", path); - - this.path = path; - this.instruction = instruction; - this.instructionId = instructionId; - } - - public String getPath() - { - return this.path; - } - - public String getInstruction() - { - return this.instruction; - } - - public String getInstructionId() - { - return this.instructionId; - } - - /** - * @see java.lang.Object#toString() - */ - @Override - public String toString() - { - StringBuilder buffer = new StringBuilder(super.toString()); - buffer.append(" (path=").append(this.path); - buffer.append(" title=").append(this.title); - buffer.append(" titleId=").append(this.titleId); - buffer.append(" description=").append(this.description); - buffer.append(" descriptionId=").append(this.descriptionId); - buffer.append(" instruction=").append(this.instruction); - buffer.append(" instructionId=").append(this.instructionId).append(")"); - return buffer.toString(); - } - } - - /** - * Represents the configuration of a conditional page in a wizard - * i.e. a <page> element that is placed within a <condition> - * element. - */ - public static class ConditionalPageConfig extends PageConfig - { - private static final long serialVersionUID = -3398913681170199314L; - - protected String condition; - - public ConditionalPageConfig(String path, String condition, - String title, String titleId, - String description, String descriptionId, - String instruction, String instructionId) - { - super(path, title, titleId, description, descriptionId, instruction, instructionId); - - // check we have a path - ParameterCheck.mandatoryString("condition", condition); - - this.condition = condition; - } - - public String getCondition() - { - return this.condition; - } - - /** - * @see java.lang.Object#toString() - */ - @Override - public String toString() - { - StringBuilder buffer = new StringBuilder(super.toString()); - buffer.append(" (path=").append(this.path); - buffer.append(" condition=").append(this.condition); - buffer.append(" title=").append(this.title); - buffer.append(" titleId=").append(this.titleId); - buffer.append(" description=").append(this.description); - buffer.append(" descriptionId=").append(this.descriptionId); - buffer.append(" instruction=").append(this.instruction); - buffer.append(" instructionId=").append(this.instructionId).append(")"); - return buffer.toString(); - } - } - - /** - * Represents the configuration of a step in a wizard - * i.e. the <step> element. - */ - public static class StepConfig extends AbstractConfig implements Serializable - { - private static final long serialVersionUID = -3707570689181455754L; - - protected String name; - protected PageConfig defaultPage; - protected List conditionalPages = - new ArrayList(3); - - public StepConfig(String name, - String title, String titleId, - String description, String descriptionId) - { - super(title, titleId, description, descriptionId); - - // check we have a name - ParameterCheck.mandatoryString("name", name); - - // check we have a title - if (this.title == null && this.titleId == null) - { - throw new IllegalArgumentException("A title or title-id attribute must be supplied for a step"); - } - - this.name = name; - } - - public String getName() - { - return this.name; - } - - public PageConfig getDefaultPage() - { - return this.defaultPage; - } - - public boolean hasConditionalPages() - { - return (this.conditionalPages.size() > 0); - } - - public List getConditionalPages() - { - return this.conditionalPages; - } - - /*package*/ void addConditionalPage(ConditionalPageConfig conditionalPage) - { - this.conditionalPages.add(conditionalPage); - } - - /*package*/ void setDefaultPage(PageConfig page) - { - this.defaultPage = page; - } - - /** - * @see java.lang.Object#toString() - */ - @Override - public String toString() - { - StringBuilder buffer = new StringBuilder(super.toString()); - buffer.append(" (name=").append(this.name); - buffer.append(" title=").append(this.title); - buffer.append(" titleId=").append(this.titleId); - buffer.append(" description=").append(this.description); - buffer.append(" descriptionId=").append(this.descriptionId); - buffer.append(" defaultPage=").append(this.defaultPage); - buffer.append(" conditionalPages=").append(this.conditionalPages).append(")"); - return buffer.toString(); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/config/WizardsElementReader.java b/war/src/main/java/org/alfresco/web/config/WizardsElementReader.java deleted file mode 100644 index ad758165e4..0000000000 --- a/war/src/main/java/org/alfresco/web/config/WizardsElementReader.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.config; - -import java.util.Iterator; - -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigException; -import org.springframework.extensions.config.xml.elementreader.ConfigElementReader; -import org.alfresco.web.config.WizardsConfigElement.ConditionalPageConfig; -import org.alfresco.web.config.WizardsConfigElement.PageConfig; -import org.alfresco.web.config.WizardsConfigElement.StepConfig; -import org.dom4j.Element; - -/** - * Custom element reader to parse config for wizards - * - * @author gavinc - */ -public class WizardsElementReader implements ConfigElementReader -{ - public static final String ELEMENT_WIZARDS = "wizards"; - public static final String ELEMENT_WIZARD = "wizard"; - public static final String ELEMENT_STEP = "step"; - public static final String ELEMENT_PAGE = "page"; - public static final String ELEMENT_CONDITION = "condition"; - - public static final String ATTR_NAME = "name"; - public static final String ATTR_MANAGED_BEAN = "managed-bean"; - public static final String ATTR_ICON = "icon"; - public static final String ATTR_TITLE = "title"; - public static final String ATTR_TITLE_ID = "title-id"; - public static final String ATTR_SUBTITLE = "subtitle"; - public static final String ATTR_SUBTITLE_ID = "subtitle-id"; - public static final String ATTR_DESCRIPTION = "description"; - public static final String ATTR_DESCRIPTION_ID = "description-id"; - public static final String ATTR_INSTRUCTION = "instruction"; - public static final String ATTR_INSTRUCTION_ID = "instruction-id"; - public static final String ATTR_ERROR_MSG_ID = "error-message-id"; - public static final String ATTR_IF = "if"; - public static final String ATTR_PATH = "path"; - - /** - * @see org.springframework.extensions.config.xml.elementreader.ConfigElementReader#parse(org.dom4j.Element) - */ - public ConfigElement parse(Element element) - { - WizardsConfigElement configElement = null; - - if (element != null) - { - String elementName = element.getName(); - if (elementName.equals(ELEMENT_WIZARDS) == false) - { - throw new ConfigException("WizardsElementReader can only parse " + - ELEMENT_WIZARDS + "elements, the element passed was '" + - elementName + "'"); - } - - configElement = new WizardsConfigElement(); - - // go through the items to show - Iterator items = element.elementIterator(ELEMENT_WIZARD); - while (items.hasNext()) - { - Element wizard = items.next(); - - String name = wizard.attributeValue(ATTR_NAME); - String bean = wizard.attributeValue(ATTR_MANAGED_BEAN); - String icon = wizard.attributeValue(ATTR_ICON); - String title = wizard.attributeValue(ATTR_TITLE); - String titleId = wizard.attributeValue(ATTR_TITLE_ID); - String subTitle = wizard.attributeValue(ATTR_SUBTITLE); - String subTitleId = wizard.attributeValue(ATTR_SUBTITLE_ID); - String description = wizard.attributeValue(ATTR_DESCRIPTION); - String descriptionId = wizard.attributeValue(ATTR_DESCRIPTION_ID); - String errorMsgId = wizard.attributeValue(ATTR_ERROR_MSG_ID); - - // create the wizard config object - WizardsConfigElement.WizardConfig wizardCfg = new WizardsConfigElement.WizardConfig( - name, bean, icon, title, titleId, subTitle, subTitleId, - description, descriptionId, errorMsgId); - - Iterator steps = wizard.elementIterator(ELEMENT_STEP); - while (steps.hasNext()) - { - StepConfig stepCfg = parseStep(steps.next()); - wizardCfg.addStep(stepCfg); - } - - configElement.addWizard(wizardCfg); - } - } - - return configElement; - } - - /** - * Parses the given element which represents a step in a wizard - * - * @param step The Element representing the step - * @return A StepConfig object - */ - protected StepConfig parseStep(Element step) - { - // get the name of the step and create the config object - String stepName = step.attributeValue(ATTR_NAME); - String stepTitle = step.attributeValue(ATTR_TITLE); - String stepTitleId = step.attributeValue(ATTR_TITLE_ID); - String stepDescription = step.attributeValue(ATTR_DESCRIPTION); - String stepDescriptionId = step.attributeValue(ATTR_DESCRIPTION_ID); - StepConfig stepCfg = new StepConfig(stepName, stepTitle, stepTitleId, - stepDescription, stepDescriptionId); - - // find and parse the default page - Element defaultPageElem = step.element(ELEMENT_PAGE); - if (defaultPageElem != null) - { - String path = defaultPageElem.attributeValue(ATTR_PATH); - String title = defaultPageElem.attributeValue(ATTR_TITLE); - String titleId = defaultPageElem.attributeValue(ATTR_TITLE_ID); - String description = defaultPageElem.attributeValue(ATTR_DESCRIPTION); - String descriptionId = defaultPageElem.attributeValue(ATTR_DESCRIPTION_ID); - String instruction = defaultPageElem.attributeValue(ATTR_INSTRUCTION); - String instructionId = defaultPageElem.attributeValue(ATTR_INSTRUCTION_ID); - - // create and set the page config on the step - stepCfg.setDefaultPage(new PageConfig(path, title, titleId, description, - descriptionId, instruction, instructionId)); - } - - // find and parse any conditions that are present - Iterator conditions = step.elementIterator(ELEMENT_CONDITION); - while (conditions.hasNext()) - { - Element conditionElem = conditions.next(); - - String ifAttr = conditionElem.attributeValue(ATTR_IF); - Element conditionalPageElem = conditionElem.element(ELEMENT_PAGE); - if (conditionalPageElem == null) - { - throw new ConfigException("A condition in step '" + stepCfg.getName() + - "' does not have a containing element"); - } - - String path = conditionalPageElem.attributeValue(ATTR_PATH); - String title = conditionalPageElem.attributeValue(ATTR_TITLE); - String titleId = conditionalPageElem.attributeValue(ATTR_TITLE_ID); - String description = conditionalPageElem.attributeValue(ATTR_DESCRIPTION); - String descriptionId = conditionalPageElem.attributeValue(ATTR_DESCRIPTION_ID); - String instruction = conditionalPageElem.attributeValue(ATTR_INSTRUCTION); - String instructionId = conditionalPageElem.attributeValue(ATTR_INSTRUCTION_ID); - - // create and add the page to the step - stepCfg.addConditionalPage(new ConditionalPageConfig(path, ifAttr, title, - titleId, description, descriptionId, instruction, instructionId)); - } - - return stepCfg; - } -} diff --git a/war/src/main/java/org/alfresco/web/data/DynamicResolver.java b/war/src/main/java/org/alfresco/web/data/DynamicResolver.java deleted file mode 100644 index 1155683764..0000000000 --- a/war/src/main/java/org/alfresco/web/data/DynamicResolver.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.data; - -/** - * Interface marker used to indicate that a property is resolved at runtime - * - * @author Kevin Roast - */ -public interface DynamicResolver -{ - -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/data/IDataContainer.java b/war/src/main/java/org/alfresco/web/data/IDataContainer.java deleted file mode 100644 index 62608fffb4..0000000000 --- a/war/src/main/java/org/alfresco/web/data/IDataContainer.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.data; - -/** - * @author kevinr - */ -public interface IDataContainer -{ - /** - * Return the currently sorted column if any - * - * @return current sorted column if any - */ - public String getCurrentSortColumn(); - - /** - * Returns the current sort direction. Only valid if a sort column is set. - * True is returned for descending sort, false for accending sort. - * - * @return true for descending sort, false for accending sort - */ - public boolean isCurrentSortDescending(); - - /** - * Returns the current page size used for this list, or -1 for no paging. - */ - public int getPageSize(); - - /** - * Return the current page the list is displaying - * - * @return Current page with zero based index - */ - public int getCurrentPage(); - - /** - * Set the current page to display. - * - * @param index Zero based page index to display - */ - public void setCurrentPage(int index); - - /** - * Return the count of max available pages - * - * @return count of max available pages - */ - public int getPageCount(); - - /** - * Returns true if a row of data is available - * - * @return true if data is available, false otherwise - */ - public boolean isDataAvailable(); - - /** - * Returns the next row of data from the data model - * - * @return next row of data as a Bean object - */ - public Object nextRow(); - - /** - * Sort the dataset using the specified sort parameters - * - * @param column Column to sort - * @param descending True for descending sort, false for ascending - * @param mode Sort mode to use (see IDataContainer constants) - */ - public void sort(String column, boolean descending, String mode); - - public final static String SORT_CASEINSENSITIVE = "case-insensitive"; - public final static String SORT_CASESENSITIVE = "case-sensitive"; -} diff --git a/war/src/main/java/org/alfresco/web/data/MergeSort.java b/war/src/main/java/org/alfresco/web/data/MergeSort.java deleted file mode 100644 index c9d98c0d82..0000000000 --- a/war/src/main/java/org/alfresco/web/data/MergeSort.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.data; - -import java.util.List; - -/** - * @author kevinr - */ -public final class MergeSort extends Sort -{ - /** - * Constructor - * - * @param data a the List of String[] data to sort - * @param column the column getter method to use on the row to sort - * @param bForward true for a forward sort, false for a reverse sort - * @param mode sort mode to use (see IDataContainer constants) - */ - public MergeSort(List data, String column, boolean bForward, String mode) - { - super(data, column, bForward, mode); - } - - - // ------------------------------------------------------------------------------ - // Sort Implementation - - /** - * Runs the Quick Sort routine on the current dataset - */ - public void sort() - { - if (this.data.size() != 0) - { - // TODO: finish this! - //mergesort(this.data, 0, this.data.size() - 1); - - /*a = this.data; - - int n = a.length; - - b = new int[(n+1) >> 1]; - mergesort(0, n-1);*/ - } - } - - - // ------------------------------------------------------------------------------ - // Private methods - - /*private static Object[] a, b; - - private static void mergesort(int lo, int hi) - { - if (lo> 1; - mergesort(lo, m); - mergesort(m+1, hi); - merge(lo, m, hi); - } - } - - private static void merge(int lo, int m, int hi) - { - int i, j, k; - - i=0; - j=lo; - - // copy first half of array a to auxiliary array b - while (j <= m) - { - b[i++] = a[j++]; - } - - i=0; - k=lo; - - // copy back next-greatest element at each time - while (k < j && j <= hi) - { - if (b[i] <= a[j]) - { - a[k++]=b[i++]; - } - else - { - a[k++]=a[j++]; - } - } - - // copy back remaining elements of first half (if any) - while (k < j) - { - a[k++] = b[i++]; - } - }*/ -} diff --git a/war/src/main/java/org/alfresco/web/data/QuickSort.java b/war/src/main/java/org/alfresco/web/data/QuickSort.java deleted file mode 100644 index 4528ff0fe6..0000000000 --- a/war/src/main/java/org/alfresco/web/data/QuickSort.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.data; - -import java.util.List; - -/** - * QuickSort - * - * Implementation of a locale sensitive Quick Sort algorithm. The sorting supports - * locale specific case sensitive, case in-sensitive and numeric data sorting. The - * numeric sorting handles integer, floating point and scientific formats, with - * short-circuit value parsing. - * - * @author Kevin Roast - */ -public final class QuickSort extends Sort -{ - /** - * Constructor - * - * @param data a the List of String[] data to sort - * @param column the column getter method to use on the row to sort - * @param bForward true for a forward sort, false for a reverse sort - * @param mode sort mode to use (see IDataContainer constants) - */ - public QuickSort(List data, String column, boolean bForward, String mode) - { - super(data, column, bForward, mode); - } - - - // ------------------------------------------------------------------------------ - // Sort Implementation - - /** - * Runs the Quick Sort routine on the current dataset - */ - public void sort() - { - if (this.data.size() != 0) - { - qsort(this.data, 0, this.data.size() - 1); - } - } - - - // ------------------------------------------------------------------------------ - // Private methods - - /** - * recursive Quicksort function. - * - * @param v the array out of which to take a slice. - * @param lower the lower bound of this slice. - * @param upper the upper bound of this slice. - */ - private void qsort(final List v, final int lower, final int upper) - { - int sliceLength = upper - lower + 1 ; - if (sliceLength > 1) - { - if (sliceLength < 7) - { - // Insertion sort on smallest datasets - for (int i=lower; i<=upper; i++) - { - if (this.bForward == true) - { - for (int j=i; j > lower && getComparator().compare(this.keys.get(j - 1), this.keys.get(j)) > 0; j--) - { - // swap both the keys and the actual row data - swap(this.keys, j - 1, j); - swap(v, j - 1, j); - } - } - else - { - for (int j=i; j > lower && getComparator().compare(this.keys.get(j - 1), this.keys.get(j)) < 0; j--) - { - // swap both the keys and the actual row data - swap(this.keys, j - 1, j); - swap(v, j - 1, j); - } - } - } - } - else - { - int pivotIndex = partition(v, lower, upper); - qsort(v, lower, pivotIndex); - qsort(v, pivotIndex + 1, upper); - } - } - } - - /** - * Partition an array in two using the pivot value that is at the - * centre of the array being partitioned. - * - * This partition implementation based on that in Winder, R - * (1993) "Developing C++ Software", Wiley, p.395. NB. This - * implementation (unlike most others) does not guarantee that - * the split point contains the pivot value. Unlike other - * implementations, it requires only < (or >) relation and not - * both < and <= (or > and >=). Also, it seems easier to program - * and to understand. - * - * @param v the List out of which to take a slice. - * @param lower the lower bound of this slice. - * @param upper the upper bound of this slice. - */ - private int partition(final List v, int lower, int upper) - { - List keys = this.keys; - Object pivotValue = keys.get((upper + lower + 1) >> 1) ; - - int size = keys.size(); - - while (lower <= upper) - { - if (this.bForward == true) - { - while (getComparator().compare(keys.get(lower), pivotValue) < 0) - { - lower++; - } - while (getComparator().compare(pivotValue, keys.get(upper)) < 0) - { - upper--; - } - } - else - { - while (getComparator().compare(keys.get(lower), pivotValue) > 0) - { - lower++; - } - while (getComparator().compare(pivotValue, keys.get(upper)) > 0) - { - upper--; - } - } - if (lower <= upper) - { - if (lower < upper) - { - swap(keys, lower, upper); - swap(v, lower, upper); - } - lower++; - upper--; - } - } - - return upper; - } - -} // end class QuickSort diff --git a/war/src/main/java/org/alfresco/web/data/Sort.java b/war/src/main/java/org/alfresco/web/data/Sort.java deleted file mode 100644 index 46894395cf..0000000000 --- a/war/src/main/java/org/alfresco/web/data/Sort.java +++ /dev/null @@ -1,483 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.data; - -import java.lang.reflect.Method; -import java.sql.Timestamp; -import java.text.CollationKey; -import java.text.Collator; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Sort - * - * Base sorting helper supports locale specific case sensitive, case in-sensitive and - * numeric data sorting. - * - * @author Kevin Roast - */ -public abstract class Sort -{ - // ------------------------------------------------------------------------------ - // Construction - - /** - * Constructor - * - * @param data a the List of String[] data to sort - * @param column the column getter method to use on the row to sort - * @param bForward true for a forward sort, false for a reverse sort - * @param mode sort mode to use (see IDataContainer constants) - */ - public Sort(List data, String column, boolean bForward, String mode) - { - this.data = data; - this.column = column; - this.bForward = bForward; - this.sortMode = mode; - - if (this.data.size() != 0) - { - // setup the Collator for our Locale - Collator collator = Collator.getInstance(Locale.getDefault()); - - // set the strength according to the sort mode - if (mode.equals(IDataContainer.SORT_CASEINSENSITIVE)) - { - collator.setStrength(Collator.SECONDARY); - } - else - { - collator.setStrength(Collator.IDENTICAL); - } - - this.keys = buildCollationKeys(collator); - } - } - - - // ------------------------------------------------------------------------------ - // Abstract Methods - - /** - * Runs the Sort routine on the current dataset - */ - public abstract void sort(); - - - // ------------------------------------------------------------------------------ - // Helper methods - - /** - * Build a list of collation keys for comparing locale sensitive strings or build - * the appropriate objects for comparison for other standard data types. - * - * @param collator the Collator object to use to build String keys - */ - @SuppressWarnings("unchecked") - protected List buildCollationKeys(Collator collator) - { - List data = this.data; - int iSize = data.size(); - List keys = new ArrayList(iSize); - - try - { - // create the Bean getter method invoker to retrieve the value for a colunm - String methodName = getGetterMethodName(this.column); - Class returnType = null;; - Method getter = null; - // there will always be at least one item to sort if we get to this method - Object bean = this.data.get(0); - try - { - getter = bean.getClass().getMethod(methodName, (Class [])null); - returnType = getter.getReturnType(); - } - catch (NoSuchMethodException nsmerr) - { - // no bean getter method found - try Map implementation - if (bean instanceof Map) - { - Object obj = ((Map)bean).get(this.column); - if (obj != null) - { - returnType = obj.getClass(); - } - else - { - if (s_logger.isInfoEnabled()) - { - s_logger.info("Unable to get return type class for RichList column: " + column + - ". Suggest set java type directly in sort component tag."); - } - returnType = Object.class; - } - } - else - { - throw new IllegalStateException("Unable to find bean getter or Map impl for column name: " + this.column); - } - } - - // create appropriate comparator instance based on data type - // using the strategy pattern so sub-classes of Sort simply invoke the - // compare() method on the comparator interface - no type info required - boolean bknownType = true; - if (returnType.equals(String.class)) - { - if (strongStringCompare == true) - { - this.comparator = new StringComparator(); - } - else - { - this.comparator = new SimpleStringComparator(); - } - } - else if (returnType.equals(Date.class)) - { - this.comparator = new DateComparator(); - } - else if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) - { - this.comparator = new BooleanComparator(); - } - else if (returnType.equals(int.class) || returnType.equals(Integer.class)) - { - this.comparator = new IntegerComparator(); - } - else if (returnType.equals(long.class) || returnType.equals(Long.class)) - { - this.comparator = new LongComparator(); - } - else if (returnType.equals(float.class) || returnType.equals(Float.class)) - { - this.comparator = new FloatComparator(); - } - else if (returnType.equals(Timestamp.class)) - { - this.comparator = new TimestampComparator(); - } - else if (DynamicResolver.class.isAssignableFrom(returnType)) - { - this.comparator = new SimpleStringComparator(); - } - else - { - if (s_logger.isDebugEnabled()) - s_logger.debug("Unsupported sort data type: " + returnType + " defaulting to .toString()"); - this.comparator = new SimpleComparator(); - bknownType = false; - } - - // create a collation key for each required column item in the dataset - for (int iIndex=0; iIndex. - * #L% - */ -package org.alfresco.web.sharepoint.auth; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.repo.management.subsystems.ActivateableBean; -import org.alfresco.repo.webdav.auth.AuthenticationDriver; -import org.alfresco.service.cmr.security.AuthenticationService; -import org.alfresco.service.cmr.security.PersonService; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - *

Abstract implementation of web authentication.

- * - * @author PavelYur - * - */ -public abstract class AbstractAuthenticationHandler implements AuthenticationDriver, ActivateableBean -{ - private final static String HEADER_WWW_AUTHENTICATE = "WWW-Authenticate"; - - protected Log logger = LogFactory.getLog(getClass()); - protected AuthenticationService authenticationService; - protected PersonService personService; - private boolean isActive = true; - - public void setAuthenticationService(AuthenticationService authenticationService) - { - this.authenticationService = authenticationService; - } - - public void setPersonService(PersonService personService) - { - this.personService = personService; - } - - public void setActive(boolean isActive) - { - this.isActive = isActive; - } - - public boolean isActive() - { - return this.isActive; - } - - /** - * Returns the value of 'WWW-Authenticate' http header that determine what type of authentication to use by - * client. - * - * @return value - */ - public abstract String getWWWAuthenticate(); - - - /* (non-Javadoc) - * @see org.alfresco.repo.webdav.auth.SharepointAuthenticationHandler#restartLoginChallenge(javax.servlet.ServletContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - public void restartLoginChallenge(ServletContext context, HttpServletRequest request, HttpServletResponse response) - { - if (logger.isDebugEnabled()) - logger.debug("Force the client to prompt for logon details"); - - response.setHeader(HEADER_WWW_AUTHENTICATE, getWWWAuthenticate()); - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/sharepoint/auth/BasicAuthenticationHandler.java b/war/src/main/java/org/alfresco/web/sharepoint/auth/BasicAuthenticationHandler.java deleted file mode 100644 index 9b06196495..0000000000 --- a/war/src/main/java/org/alfresco/web/sharepoint/auth/BasicAuthenticationHandler.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.sharepoint.auth; - -import java.io.IOException; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.alfresco.repo.SessionUser; -import org.alfresco.repo.management.subsystems.ActivateableBean; -import org.alfresco.repo.security.authentication.AuthenticationComponent; -import org.alfresco.repo.security.authentication.AuthenticationException; -import org.alfresco.repo.security.authentication.external.RemoteUserMapper; -import org.alfresco.repo.web.auth.AuthenticationListener; -import org.alfresco.repo.web.auth.TicketCredentials; -import org.alfresco.repo.web.auth.BasicAuthCredentials; -import org.alfresco.repo.webdav.auth.SharepointConstants; -import org.alfresco.web.bean.repository.User; -import org.apache.commons.codec.binary.Base64; - -/** - *

- * BASIC web authentication implementation. - *

- * - * @author PavelYur - */ -public class BasicAuthenticationHandler extends AbstractAuthenticationHandler implements SharepointConstants -{ - private final static String HEADER_AUTHORIZATION = "Authorization"; - - private final static String BASIC_START = "Basic"; - - private AuthenticationListener authenticationListener; - protected RemoteUserMapper remoteUserMapper; - protected AuthenticationComponent authenticationComponent; - - /** - * Set the authentication listener - */ - public void setAuthenticationListener(AuthenticationListener authenticationListener) - { - this.authenticationListener = authenticationListener; - } - - /* - * (non-Javadoc) - * @see - * org.alfresco.repo.webdav.auth.SharepointAuthenticationHandler#authenticateRequest(javax.servlet.ServletContext, - * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - public boolean authenticateRequest(ServletContext context, HttpServletRequest request, HttpServletResponse response) - throws IOException, ServletException - { - if (isUserAuthenticated(context, request)) - { - return true; - } - else - { - // Unlike multi-stage authentication protocols like Kerberos / NTLM we have only one possible response to an - // unauthenticated user - restartLoginChallenge(context, request, response); - return false; - } - } - - /** - * Returns true if the user is authenticated and their details are cached in the session - * - * @param context - * the servlet context - * @param request - * the servlet request - * @return true, if the user is authenticated - * @throws IOException - * Signals that an I/O exception has occurred. - * @throws ServletException - * On other errors. - */ - public boolean isUserAuthenticated(ServletContext context, HttpServletRequest request) throws IOException, - ServletException - { - String authHdr = request.getHeader(HEADER_AUTHORIZATION); - HttpSession session = request.getSession(false); - SessionUser sessionUser = session == null ? null : (SessionUser) session.getAttribute(USER_SESSION_ATTRIBUTE); - if (sessionUser == null) - { - if (remoteUserMapper != null && (!(remoteUserMapper instanceof ActivateableBean) || ((ActivateableBean) remoteUserMapper).isActive())) - { - String userId = remoteUserMapper.getRemoteUser(request); - if (userId != null) - { - // authenticated by other - authenticationComponent.setCurrentUser(userId); - - request.getSession().setAttribute(USER_SESSION_ATTRIBUTE, new User(userId, authenticationService.getCurrentTicket(), personService.getPerson(userId))); - return true; - } - } - if (authHdr != null && authHdr.length() > 5 && authHdr.substring(0, 5).equalsIgnoreCase(BASIC_START)) - { - String basicAuth = new String(Base64.decodeBase64(authHdr.substring(5).getBytes())); - String username = null; - String password = null; - - int pos = basicAuth.indexOf(":"); - if (pos != -1) - { - username = basicAuth.substring(0, pos); - password = basicAuth.substring(pos + 1); - } - else - { - username = basicAuth; - password = ""; - } - - try - { - if (logger.isDebugEnabled()) - logger.debug("Authenticating user '" + username + "'"); - - authenticationService.authenticate(username, password.toCharArray()); - - // Normalize the user ID taking into account case sensitivity settings - username = authenticationService.getCurrentUserName(); - - if (logger.isDebugEnabled()) - logger.debug("Authenticated user '" + username + "'"); - - authenticationListener.userAuthenticated(new BasicAuthCredentials(username, password)); - - request.getSession() - .setAttribute( - USER_SESSION_ATTRIBUTE, - new User(username, authenticationService.getCurrentTicket(), personService - .getPerson(username))); - - return true; - } - catch (AuthenticationException ex) - { - authenticationListener.authenticationFailed(new BasicAuthCredentials(username, password), ex); - } - } - } - else - { - try - { - authenticationService.validate(sessionUser.getTicket()); - authenticationListener.userAuthenticated(new TicketCredentials(sessionUser.getTicket())); - return true; - } - catch (AuthenticationException ex) - { - authenticationListener.authenticationFailed(new TicketCredentials(sessionUser.getTicket()), ex); - session.invalidate(); - } - } - - return false; - } - - @Override - public String getWWWAuthenticate() - { - return "Basic realm=\"Alfresco Server\""; - } - - public void setRemoteUserMapper(RemoteUserMapper remoteUserMapper) - { - this.remoteUserMapper = remoteUserMapper; - } - - public void setAuthenticationComponent(AuthenticationComponent authenticationComponent) - { - this.authenticationComponent = authenticationComponent; - } - - -} diff --git a/war/src/main/java/org/alfresco/web/sharepoint/auth/kerberos/KerberosAuthenticationHandler.java b/war/src/main/java/org/alfresco/web/sharepoint/auth/kerberos/KerberosAuthenticationHandler.java deleted file mode 100644 index 21ec8f6fbc..0000000000 --- a/war/src/main/java/org/alfresco/web/sharepoint/auth/kerberos/KerberosAuthenticationHandler.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.sharepoint.auth.kerberos; - -import java.io.IOException; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.alfresco.repo.SessionUser; -import org.alfresco.repo.web.auth.WebCredentials; -import org.alfresco.repo.webdav.auth.BaseKerberosAuthenticationFilter; -import org.alfresco.repo.webdav.auth.SharepointConstants; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.bean.repository.User; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - *

- * Kerberos SSO web authentication implementation. - *

- */ -public class KerberosAuthenticationHandler extends BaseKerberosAuthenticationFilter -{ - // Debug logging - private static Log logger = LogFactory.getLog(KerberosAuthenticationHandler.class); - - @Override - protected void init() throws ServletException - { - setUserAttributeName(SharepointConstants.USER_SESSION_ATTRIBUTE); - super.init(); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.webdav.auth.BaseSSOAuthenticationFilter#onValidateFailed(javax.servlet.ServletContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, javax.servlet.http.HttpSession) - */ - @Override - protected void onValidateFailed(ServletContext sc, HttpServletRequest req, HttpServletResponse res, HttpSession session, WebCredentials credentials) - throws IOException - { - super.onValidateFailed(sc, req, res, session, credentials); - - // Restart the login challenge process if validation fails - restartLoginChallenge(sc, req, res); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.webdav.auth.BaseAuthenticationFilter#createUserObject(java.lang.String, java.lang.String, org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.cmr.repository.NodeRef) - */ - @Override - protected SessionUser createUserObject(String userName, String ticket, NodeRef personNode, NodeRef homeSpaceRef) - { - // Create a web client user object - User user = new User( userName, ticket, personNode); - user.setHomeSpaceId( homeSpaceRef.getId()); - - return user; - } - - @Override - protected Log getLogger() - { - return logger; - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/sharepoint/auth/ntlm/NtlmAuthenticationHandler.java b/war/src/main/java/org/alfresco/web/sharepoint/auth/ntlm/NtlmAuthenticationHandler.java deleted file mode 100644 index eec8cae32b..0000000000 --- a/war/src/main/java/org/alfresco/web/sharepoint/auth/ntlm/NtlmAuthenticationHandler.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.sharepoint.auth.ntlm; - -import java.io.IOException; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.alfresco.repo.SessionUser; -import org.alfresco.repo.web.auth.WebCredentials; -import org.alfresco.repo.webdav.auth.BaseNTLMAuthenticationFilter; -import org.alfresco.repo.webdav.auth.SharepointConstants; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.web.bean.repository.User; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - *

- * NTLM SSO web authentication implementation. - *

- */ -public class NtlmAuthenticationHandler extends BaseNTLMAuthenticationFilter -{ - // Debug logging - private static Log logger = LogFactory.getLog(NtlmAuthenticationHandler.class); - - @Override - protected void init() throws ServletException - { - setUserAttributeName(SharepointConstants.USER_SESSION_ATTRIBUTE); - super.init(); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.webdav.auth.BaseSSOAuthenticationFilter#onValidateFailed(javax.servlet.ServletContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, javax.servlet.http.HttpSession) - */ - @Override - protected void onValidateFailed(ServletContext sc, HttpServletRequest req, HttpServletResponse res, HttpSession session, WebCredentials credentials) - throws IOException - { - super.onValidateFailed(sc, req, res, session, credentials); - - // Restart the login challenge process if validation fails - restartLoginChallenge(sc, req, res); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.webdav.auth.BaseAuthenticationFilter#createUserObject(java.lang.String, java.lang.String, org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.cmr.repository.NodeRef) - */ - @Override - protected SessionUser createUserObject(String userName, String ticket, NodeRef personNode, NodeRef homeSpaceRef) - { - // Create a web client user object - User user = new User( userName, ticket, personNode); - user.setHomeSpaceId( homeSpaceRef.getId()); - - return user; - } - - @Override - protected Log getLogger() - { - return logger; - } -} \ No newline at end of file diff --git a/war/src/main/java/org/alfresco/web/ui/common/ComponentConstants.java b/war/src/main/java/org/alfresco/web/ui/common/ComponentConstants.java deleted file mode 100644 index 43494da818..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/ComponentConstants.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common; - -/** - * @author Kevin Roast - */ -public final class ComponentConstants -{ - public static final String JAVAX_FACES_INPUT = "javax.faces.Input"; - public static final String JAVAX_FACES_TEXT = "javax.faces.Text"; - public static final String JAVAX_FACES_TEXTAREA = "javax.faces.Textarea"; - public static final String JAVAX_FACES_OUTPUT = "javax.faces.Output"; - public static final String JAVAX_FACES_GRID = "javax.faces.Grid"; - public static final String JAVAX_FACES_PANEL = "javax.faces.Panel"; - public static final String JAVAX_FACES_PANELGROUP = "javax.faces.HtmlPanelGroup"; - public static final String JAVAX_FACES_CHECKBOX = "javax.faces.Checkbox"; - public static final String JAVAX_FACES_SELECT_BOOLEAN = "javax.faces.SelectBoolean"; - public static final String JAVAX_FACES_GRAPHIC = "javax.faces.Graphic"; - public static final String JAVAX_FACES_PARAMETER = "javax.faces.Parameter"; - public static final String JAVAX_FACES_MENU = "javax.faces.Menu"; - public static final String JAVAX_FACES_BUTTON = "javax.faces.Button"; - public static final String JAVAX_FACES_SELECT_ITEMS = "javax.faces.SelectItems"; - - - /** - * Private constructor - */ - private ComponentConstants() - { - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/NodeListUtils.java b/war/src/main/java/org/alfresco/web/ui/common/NodeListUtils.java deleted file mode 100644 index fd4b5f50d1..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/NodeListUtils.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common; - -import java.util.List; - -import org.alfresco.web.bean.repository.Node; - -/** - * Helper class to get next or previos node from the list of nodes. -* -* @author vdanilchenko -* @since 4.1.3 -*/ -public class NodeListUtils -{ - /** - * @param nodes the list of the nodes - * @param currentNodeId the current node ID - */ - public static Node nextItem(List nodes, String currentNodeId) - { - Node next = null; - - // perform a linear search - this is slow but stateless - // otherwise we would have to manage state of last selected node - // this gets very tricky as this bean is instantiated once and never - // reset - it does not know when the document has changed etc. - for (int i=0; i nodes, String currentNodeId) - { - Node previous = null; - - // perform a linear search - this is slow but stateless - // otherwise we would have to manage state of last selected node - // this gets very tricky as this bean is instantiated once and never - // reset - it does not know when the document has changed etc. - for (int i=0; i. - * #L% - */ -package org.alfresco.web.ui.common; - -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.web.bean.repository.DataDictionary; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.app.Application; - -import org.springframework.web.jsf.FacesContextUtils; - -import java.util.Comparator; -import java.util.Date; -import java.util.Map; - -import javax.faces.context.FacesContext; - -/** - * Comparator to sort the list of nodes according theirs properties and sort order - * - * @author vdanilchenko - * @since 4.1.3 - */ -public class NodePropertyComparator implements Comparator -{ - private String propertyName; - private boolean isAscending; - private DataDictionary dataDictionary; - - /** - * @param propertyName the property name to sort - * @param isAscending sort order - */ - public NodePropertyComparator(String propertyName, boolean isAscending) - { - super(); - this.propertyName = propertyName; - this.isAscending = isAscending; - - FacesContext context = FacesContext.getCurrentInstance(); - dataDictionary = (DataDictionary)FacesContextUtils.getRequiredWebApplicationContext(context).getBean(Application.BEAN_DATA_DICTIONARY); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public int compare(Object node1, Object node2) - { - Map nodeProperties1 = ((Node)node1).getProperties(); - Map nodeProperties2 = ((Node)node2).getProperties(); - PropertyDefinition pd1 = dataDictionary.getPropertyDefinition((Node)node1, propertyName); - PropertyDefinition pd2 = dataDictionary.getPropertyDefinition((Node)node2, propertyName); - Comparable propertyValue1, propertyValue2; - if((pd1 != null) && (pd2 != null)) - { - String typeName = pd1.getDataType().getName().getLocalName(); - - if(typeName.equals("datetime")) - { - propertyValue1 = (Date) nodeProperties1.get(propertyName); - propertyValue2 = (Date) nodeProperties2.get(propertyName); - } - else if(typeName.equals("long")) - { - propertyValue1 = (Long) nodeProperties1.get(propertyName); - propertyValue2 = (Long) nodeProperties2.get(propertyName); - } - else if(typeName.equals("boolean")) - { - propertyValue1 = (Boolean) nodeProperties1.get(propertyName); - propertyValue2 = (Boolean) nodeProperties2.get(propertyName); - } - //string types: text, mltext - //non comparable types: locale, content - else - { - propertyValue1 = nodeProperties1.get(propertyName).toString(); - propertyValue2 = nodeProperties2.get(propertyName).toString(); - } - } - //additional properties doesn't contains in the node properties - //their type can't be resolved using DataDictionary - //QNameNodeMap resolves them on first invocation and puts them into the map of node properties - else - { - if(propertyName.equals("size")) - { - propertyValue1 = (Long) nodeProperties1.get(propertyName); - propertyValue2 = (Long) nodeProperties2.get(propertyName); - } - else - { - propertyValue1 = nodeProperties1.get(propertyName).toString(); - propertyValue2 = nodeProperties2.get(propertyName).toString(); - } - } - - if(isAscending) - { - return propertyValue1.compareTo(propertyValue2); - } - return propertyValue2.compareTo(propertyValue1); - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/PanelGenerator.java b/war/src/main/java/org/alfresco/web/ui/common/PanelGenerator.java deleted file mode 100644 index 0580a254e8..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/PanelGenerator.java +++ /dev/null @@ -1,344 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common; - -import java.io.IOException; -import java.io.Writer; - -/** - * Helper to generate the rounded panel HTML templates - * - * @author kevinr - */ -public final class PanelGenerator -{ - public static void generatePanel(Writer out, String contextPath, String panel, String inner) - throws IOException - { - generatePanel(out, contextPath, panel, inner, BGCOLOR_WHITE); - } - - public static void generatePanel(Writer out, String contextPath, String panel, String inner, String bgColor) - throws IOException - { - generatePanel(out, contextPath, panel, inner, bgColor, false); - } - - public static void generatePanel(Writer out, String contextPath, String panel, String inner, String bgColor, boolean dialog) - throws IOException - { - generatePanelStart(out, contextPath, panel, bgColor, dialog); - out.write(inner); - generatePanelEnd(out, contextPath, panel); - } - - public static void generatePanelStart(Writer out, String contextPath, String panel, String bgColor) - throws IOException - { - generatePanelStart(out, contextPath, panel, bgColor, false); - } - - public static void generatePanelStart(final Writer out, - final String contextPath, - final String panel, - final String bgColor, - final boolean dialog) - throws IOException - { - out.write(""); - out.write(""); - - out.write(""); - - out.write(""); - - out.write(""); - - out.write(""); - - out.write(""); - - out.write("
"); - } - - public static void generatePanelStartWithBgImg(final Writer out, - final String contextPath, final String panel, String bgColor) - throws IOException - { - out.write(""); - out.write(""); - - out.write(""); - - out.write(""); - - out.write(""); - - out.write(""); - - out.write(""); - - out.write("
"); - } - - public static void generatePanelEnd(final Writer out, - final String contextPath, - final String panel) - throws IOException - { - out.write("
"); - } - - public static void generatePanelEndWithBgImg(final Writer out, - final String contextPath, - final String panel) - throws IOException - { - out.write("
"); -} - - public static void generateTitledPanelMiddle(final Writer out, - final String contextPath, - final String titlePanel, - final String contentPanel, - final String contentBgColor) - throws IOException - { - // generate the expanded part, just under the title - out.write(""); - - out.write(""); - - out.write(""); - - out.write(""); - - out.write(""); - } - - public static void generateExpandedTitledPanelMiddle(final Writer out, - final String contextPath, - final String titlePanel, - final String expandedTitlePanel, - final String contentPanel, - final String contentBgColor) - throws IOException - { - // generate the expanded part, just under the title - out.write(""); - - out.write(""); - - out.write(""); - - out.write(""); - - out.write(""); - } - - public final static String BGCOLOR_WHITE = "#FFFFFF"; -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/ReportedException.java b/war/src/main/java/org/alfresco/web/ui/common/ReportedException.java deleted file mode 100644 index 830f06213b..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/ReportedException.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common; - -import javax.transaction.UserTransaction; - -import org.alfresco.repo.transaction.RetryingTransactionHelper; - -/** - * Unchecked exception wrapping an already-reported exception. The dialog code can use this to - * detect whether or not to report further to the user. - * - * @author Derek Hulley - * @since 3.1 - */ -public class ReportedException extends RuntimeException -{ - private static final long serialVersionUID = -4179045854462002741L; - - public ReportedException(Throwable e) - { - super(e); - } - - /** - * Throws the given exception if we are still in an active transaction, - * this ensures that we cross the transaction boundary and thus cause - * the transaction to rollback. - * - * @param error The error to be thrown - */ - public static void throwIfNecessary(Throwable error) - { - if (error != null) - { - UserTransaction txn = RetryingTransactionHelper.getActiveUserTransaction(); - if (txn != null) - { - throw new ReportedException(error); - } - } - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/SortableSelectItem.java b/war/src/main/java/org/alfresco/web/ui/common/SortableSelectItem.java deleted file mode 100644 index 7ae2a74ba3..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/SortableSelectItem.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common; - -import javax.faces.model.SelectItem; - -/** - * Wrapper class to facilitate case-insensitive sorting functionality against our SelectItem objects - * - * @author Kevin Roast - */ -public final class SortableSelectItem extends SelectItem implements Comparable -{ - public SortableSelectItem(String value, String label, String sort) - { - super(value, label); - this.sort = sort; - } - - public int compareTo(Object obj2) - { - SortableSelectItem s2 = ((SortableSelectItem)obj2); - if (this.sort == null) - { - if (s2 == null || s2.sort == null) - { - return 0; - } - return -1; - } - else - { - if (s2 == null || s2.sort == null) - { - return 1; - } - return this.sort.compareToIgnoreCase( s2.sort ); - } - } - - private String sort; -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/Utils.java b/war/src/main/java/org/alfresco/web/ui/common/Utils.java deleted file mode 100644 index 0aa30b0f9e..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/Utils.java +++ /dev/null @@ -1,1253 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common; - -import java.io.IOException; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.StringTokenizer; - -import javax.faces.application.FacesMessage; -import javax.faces.component.NamingContainer; -import javax.faces.component.UIComponent; -import javax.faces.component.UIForm; -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; -import javax.faces.el.EvaluationException; -import javax.faces.el.MethodBinding; -import javax.faces.event.AbortProcessingException; -import javax.faces.event.ActionEvent; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.filesys.repo.ContentContext; -import org.alfresco.jlan.server.config.ServerConfigurationAccessor; -import org.alfresco.jlan.server.core.SharedDevice; -import org.alfresco.jlan.server.core.SharedDeviceList; -import org.alfresco.jlan.server.filesys.DiskSharedDevice; -import org.alfresco.jlan.server.filesys.FilesystemsConfigSection; -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.model.filefolder.FileFolderServiceImpl.InvalidTypeException; -import org.alfresco.repo.security.permissions.AccessDeniedException; -import org.alfresco.repo.webdav.WebDAVHelper; -import org.alfresco.repo.webdav.WebDAVServlet; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.model.FileFolderService; -import org.alfresco.service.cmr.model.FileInfo; -import org.alfresco.service.cmr.model.FileNotFoundException; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NoTransformerException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.security.PersonService; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.alfresco.util.EqualsHelper; -import org.alfresco.util.Pair; -import org.alfresco.util.SearchLanguageConversion; -import org.alfresco.web.app.Application; -import org.alfresco.web.app.servlet.DownloadContentServlet; -import org.alfresco.web.app.servlet.ExternalAccessServlet; -import org.alfresco.web.bean.NavigationBean; -import org.alfresco.web.bean.repository.Node; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.data.IDataContainer; -import org.alfresco.web.ui.common.component.UIStatusMessage; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.myfaces.shared_impl.renderkit.html.HtmlFormRendererBase; -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.webscripts.ui.common.StringUtils; -import org.springframework.web.jsf.FacesContextUtils; - -/** - * Class containing misc helper methods used by the JSF components. - * - * @author Kevin Roast - */ -public final class Utils extends StringUtils -{ - public static final String USER_AGENT_FIREFOX = "Firefox"; - public static final String USER_AGENT_MSIE = "MSIE"; - private static final String MSG_TIME_PATTERN = "time_pattern"; - private static final String MSG_DATE_PATTERN = "date_pattern"; - private static final String MSG_DATE_TIME_PATTERN = "date_time_pattern"; - - private static final Log logger = LogFactory.getLog(Utils.class); - - /** RegEx to split a String on the first space. */ - public static final String ON_FIRST_SPACE = " +"; - - static - { - tagWhiteList.add("STRIKE"); - } - /** - * Private constructor - */ - private Utils() - { - } - - /** - * Helper to output an attribute to the output stream - * - * @param out ResponseWriter - * @param attr attribute value object (cannot be null) - * @param mapping mapping to output as e.g. style="..." - * - * @throws IOException - */ - public static void outputAttribute(ResponseWriter out, Object attr, String mapping) - throws IOException - { - if (attr != null) - { - out.write(' '); - out.write(mapping); - out.write("=\""); - out.write(attr.toString()); - out.write('"'); - } - } - - /** - * Get the hidden field name for any action component. - * - * All components that wish to simply encode a form value with their client ID can reuse the same - * hidden field within the parent form. NOTE: components which use this method must only encode - * their client ID as the value and nothing else! - * - * Build a shared field name from the parent form name and the string "act". - * - * @return hidden field name shared by all action components within the Form. - */ - public static String getActionHiddenFieldName(FacesContext context, UIComponent component) - { - return Utils.getParentForm(context, component).getClientId(context) + NamingContainer.SEPARATOR_CHAR + "act"; - } - - /** - * Helper to recursively render a component and it's child components - * - * @param context FacesContext - * @param component UIComponent - * - * @throws IOException - */ - public static void encodeRecursive(FacesContext context, UIComponent component) - throws IOException - { - if (component.isRendered() == true) - { - component.encodeBegin(context); - - // follow the spec for components that render their children - if (component.getRendersChildren() == true) - { - component.encodeChildren(context); - } - else - { - if (component.getChildCount() != 0) - { - for (Iterator i=component.getChildren().iterator(); i.hasNext(); /**/) - { - encodeRecursive(context, (UIComponent)i.next()); - } - } - } - - component.encodeEnd(context); - } - } - - /** - * Generate the JavaScript to submit set the specified hidden Form field to the - * supplied value and submit the parent Form. - * - * NOTE: the supplied hidden field name is added to the Form Renderer map for output. - * - * @param context FacesContext - * @param component UIComponent to generate JavaScript for - * @param fieldId Hidden field id to set value for - * @param fieldValue Hidden field value to set hidden field too on submit - * - * @return JavaScript event code - */ - public static String generateFormSubmit(FacesContext context, UIComponent component, String fieldId, String fieldValue) - { - return generateFormSubmit(context, component, fieldId, fieldValue, false, null); - } - - /** - * Generate the JavaScript to submit set the specified hidden Form field to the - * supplied value and submit the parent Form. - * - * NOTE: the supplied hidden field name is added to the Form Renderer map for output. - * - * @param context FacesContext - * @param component UIComponent to generate JavaScript for - * @param fieldId Hidden field id to set value for - * @param fieldValue Hidden field value to set hidden field too on submit - * @param params Optional map of param name/values to output - * - * @return JavaScript event code - */ - public static String generateFormSubmit(FacesContext context, UIComponent component, String fieldId, - String fieldValue, Map params) - { - return generateFormSubmit(context, component, fieldId, fieldValue, false, params); - } - - /** - * Generate the JavaScript to submit set the specified hidden Form field to the - * supplied value and submit the parent Form. - * - * NOTE: the supplied hidden field name is added to the Form Renderer map for output. - * - * @param context FacesContext - * @param component UIComponent to generate JavaScript for - * @param fieldId Hidden field id to set value for - * @param fieldValue Hidden field value to set hidden field too on submit - * @param valueIsParam Determines whether the fieldValue parameter should be treated - * as a parameter in the generated JavaScript, false will treat - * the value i.e. surround it with single quotes - * @param params Optional map of param name/values to output - * - * @return JavaScript event code - */ - public static String generateFormSubmit(FacesContext context, UIComponent component, String fieldId, - String fieldValue, boolean valueIsParam, Map params) - { - UIForm form = Utils.getParentForm(context, component); - if (form == null) - { - throw new IllegalStateException("Must nest components inside UIForm to generate form submit!"); - } - - String formClientId = form.getClientId(context); - - StringBuilder buf = new StringBuilder(200); - buf.append("document.forms['"); - buf.append(formClientId); - buf.append("']['"); - buf.append(fieldId); - buf.append("'].value="); - if (valueIsParam == false) - { - buf.append("'"); - } - buf.append(Utils.encode(fieldValue)); - if (valueIsParam == false) - { - buf.append("'"); - } - buf.append(";"); - - if (params != null) - { - for (String name : params.keySet()) - { - buf.append("document.forms['"); - buf.append(formClientId); - buf.append("']['"); - buf.append(name); - buf.append("'].value='"); - String val = params.get(name); - if (val != null) - { - val = Utils.encode(val); - } - val = replace(val, "\\", "\\\\"); // encode escape character - val = replace(val, "'", "\\'"); // encode single quote as we wrap string with that - buf.append(val); - buf.append("';"); - - // weak, but this seems to be the way Sun RI do it... - //FormRenderer.addNeededHiddenField(context, name); - HtmlFormRendererBase.addHiddenCommandParameter(context, form, name); - } - } - - buf.append("document.forms['"); - buf.append(formClientId); - buf.append("'].submit();"); - - if (valueIsParam == false) - { - buf.append("return false;"); - } - - // weak, but this seems to be the way Sun RI do it... - //FormRenderer.addNeededHiddenField(context, fieldId); - HtmlFormRendererBase.addHiddenCommandParameter(context, form, fieldId); - - return buf.toString(); - } - - /** - * Generate the JavaScript to submit the parent Form. - * - * @param context FacesContext - * @param component UIComponent to generate JavaScript for - * - * @return JavaScript event code - */ - public static String generateFormSubmit(FacesContext context, UIComponent component) - { - UIForm form = Utils.getParentForm(context, component); - if (form == null) - { - throw new IllegalStateException("Must nest components inside UIForm to generate form submit!"); - } - - String formClientId = form.getClientId(context); - - StringBuilder buf = new StringBuilder(48); - - buf.append("document.forms['"); - buf.append(formClientId); - buf.append("'].submit()"); - - buf.append(";return false;"); - - return buf.toString(); - } - - /** - * Enum representing the client URL type to generate - */ - public enum URLMode {HTTP_DOWNLOAD, HTTP_INLINE, WEBDAV, CIFS, SHOW_DETAILS, BROWSE, FTP} - - /** - * Generates a URL for the given usage for the given node. If the URL cannot be generated - * then null is returned. - * - * The supported values for the usage parameter are of URLMode enum type - * @see URLMode - * - * @param context Faces context - * @param node The node to generate the URL for - * @param name Name to use for the download file part of the link if any - * @param usage What the URL is going to be used for - * - * @return The URL for the requested usage without the context path - */ - public static String generateURL(FacesContext context, Node node, String name, URLMode usage) - { - String url = null; - - switch (usage) - { - case WEBDAV: - { - // calculate a WebDAV URL for the given node - FileFolderService fileFolderService = Repository.getServiceRegistry( - context).getFileFolderService(); - try - { - NodeRef rootNode = WebDAVServlet.getWebdavRootNode(); - if (rootNode != null) - { - // build up the webdav url - StringBuilder path = new StringBuilder("/").append(WebDAVServlet.WEBDAV_PREFIX); - - if (!rootNode.equals(node.getNodeRef())) - { - - List paths = fileFolderService.getNamePath(rootNode, node.getNodeRef()); - - // build up the path skipping the first path as it is the root folder - for (int x = 0; x < paths.size(); x++) - { - path.append("/").append(WebDAVHelper.encodeURL(paths.get(x).getName(), getUserAgent(context))); - } - } - url = path.toString(); - } - } - catch (AccessDeniedException e) - { - // cannot build path if user don't have access all the way up - } - catch (FileNotFoundException nodeErr) - { - // cannot build path if file no longer exists - } - catch (InvalidTypeException e) - { - // primary path does not translate to a file/folder path. - } - break; - } - - case CIFS: - { - // calculate a CIFS path for the given node - - // get hold of the node service, cifsServer and navigation bean - ServiceRegistry serviceRegistry = Repository.getServiceRegistry(context); - NodeService nodeService = serviceRegistry.getNodeService(); - FileFolderService fileFolderService = serviceRegistry.getFileFolderService(); - NavigationBean navBean = (NavigationBean)context.getExternalContext(). - getSessionMap().get(NavigationBean.BEAN_NAME); - ServerConfigurationAccessor serverConfiguration = (ServerConfigurationAccessor)FacesContextUtils.getRequiredWebApplicationContext( - context).getBean("fileServerConfiguration"); - - if (nodeService != null && fileFolderService != null && navBean != null && serverConfiguration != null) - { - // Resolve CIFS network folder location for this node - FilesystemsConfigSection filesysConfig = (FilesystemsConfigSection)serverConfiguration.getConfigSection(FilesystemsConfigSection.SectionName); - DiskSharedDevice diskShare = null; - - SharedDeviceList shares = filesysConfig.getShares(); - Enumeration shareEnum = shares.enumerateShares(); - - while (shareEnum.hasMoreElements() && diskShare == null) - { - SharedDevice curShare = shareEnum.nextElement(); - if (curShare.getContext() instanceof ContentContext) - { - // ALF-6863: Check if the node has a path beneath contentContext.getRootNode() - ContentContext contentContext = (ContentContext) curShare.getContext(); - NodeRef rootNode = contentContext.getRootNode(); - if (node.getNodeRef().equals(rootNode)) - { - diskShare = (DiskSharedDevice) curShare; - break; - } - try - { - fileFolderService.getNamePath(rootNode, node.getNodeRef()); - if (logger.isDebugEnabled()) - { - logger.debug(" Node " + node.getName() + " HAS been found on " + contentContext.getDeviceName()); - } - diskShare = (DiskSharedDevice) curShare; - break; - } - catch (FileNotFoundException ex) - { - if (logger.isDebugEnabled()) - { - logger.debug(" Node " + node.getName() + " HAS NOT been found on " + contentContext.getDeviceName()); - } - // There is no such node on this SharedDevice, continue - continue; - } - catch (InvalidTypeException e) - { - if (logger.isDebugEnabled()) - { - logger.debug(" Node " + node.getName() + " HAS NOT been found on " + contentContext.getDeviceName()); - } - // primary path does not translate to a file/folder path. - } - } - } - - if (diskShare != null) - { - ContentContext contentCtx = (ContentContext)diskShare.getContext(); - NodeRef rootNode = contentCtx.getRootNode(); - try - { - if (!EqualsHelper.nullSafeEquals(rootNode, node.getNodeRef())) - { - String userAgent = Utils.getUserAgent(context); - final boolean isIE = Utils.USER_AGENT_MSIE.equals(userAgent); - - if (isIE) - { - url = Repository.getNamePathEx(context, node.getNodePath(), rootNode, "\\", "file:///" + navBean.getCIFSServerPath(diskShare)); - } - else - { - // build up the CIFS url - StringBuilder path = new StringBuilder("file:///").append(navBean.getCIFSServerPath(diskShare)); - List paths = fileFolderService.getNamePath(rootNode, node.getNodeRef()); - - // build up the path skipping the first path as it is the root folder - for (int x = 0; x < paths.size(); x++) - { - path.append("\\").append(WebDAVHelper.encodeURL(paths.get(x).getName(), userAgent)); - } - url = path.toString(); - } - } - } - catch (AccessDeniedException e) - { - // cannot build path if user don't have access all the way up - } - catch (FileNotFoundException nodeErr) - { - // cannot build path if file no longer exists - } - catch (InvalidNodeRefException nodeErr) - { - // cannot build path if node no longer exists - } - } - } - break; - } - - case HTTP_DOWNLOAD: - { - url = DownloadContentServlet.generateDownloadURL(node.getNodeRef(), name); - break; - } - - case HTTP_INLINE: - { - url = DownloadContentServlet.generateBrowserURL(node.getNodeRef(), name); - break; - } - - case SHOW_DETAILS: - { - DictionaryService dd = Repository.getServiceRegistry(context).getDictionaryService(); - - // default to showing details of content - String outcome = ExternalAccessServlet.OUTCOME_DOCDETAILS; - - // if the node is a type of folder then make the outcome to show space details - if ((dd.isSubClass(node.getType(), ContentModel.TYPE_FOLDER)) || - (dd.isSubClass(node.getType(), ApplicationModel.TYPE_FOLDERLINK))) - { - outcome = ExternalAccessServlet.OUTCOME_SPACEDETAILS; - } - - // build the url - url = ExternalAccessServlet.generateExternalURL(outcome, - Repository.getStoreRef().getProtocol() + "/" + - Repository.getStoreRef().getIdentifier() + "/" + node.getId()); - break; - } - - case BROWSE: - { - url = ExternalAccessServlet.generateExternalURL(ExternalAccessServlet.OUTCOME_BROWSE, - Repository.getStoreRef().getProtocol() + "/" + - Repository.getStoreRef().getIdentifier() + "/" + node.getId()); - } - - case FTP: - { - // not implemented yet! - break; - } - } - - return url; - } - - /** - * Generates a URL for the given usage for the given node. - * - * The supported values for the usage parameter are of URLMode enum type - * @see URLMode - * - * @param context Faces context - * @param node The node to generate the URL for - * @param usage What the URL is going to be used for - * - * @return The URL for the requested usage without the context path - */ - public static String generateURL(FacesContext context, Node node, URLMode usage) - { - return generateURL(context, node, node.getName(), usage); - } - - /** - * Build a context path safe image tag for the supplied image path. - * Image path should be supplied with a leading slash '/'. - * - * @param context FacesContext - * @param image The local image path from the web folder with leading slash '/' - * @param width Width in pixels - * @param height Height in pixels - * @param alt Optional alt/title text - * @param onclick JavaScript onclick event handler code - * - * @return Populated img tag - */ - public static String buildImageTag(FacesContext context, String image, int width, int height, - String alt, String onclick) - { - return buildImageTag(context, image, width, height, alt, onclick, null); - } - - /** - * Build a context path safe image tag for the supplied image path. - * Image path should be supplied with a leading slash '/'. - * - * @param context FacesContext - * @param image The local image path from the web folder with leading slash '/' - * @param width Width in pixels - * @param height Height in pixels - * @param alt Optional alt/title text - * @param onclick JavaScript onclick event handler code - * @param verticalAlign Optional HTML alignment value - * - * @return Populated img tag - */ - public static String buildImageTag(FacesContext context, String image, int width, int height, - String alt, String onclick, String verticalAlign) - { - return buildImageTag(context, image, width, height, alt, onclick, verticalAlign, null); - } - - /** - * Build a context path safe image tag for the supplied image path. - * Image path should be supplied with a leading slash '/'. - * - * @param context FacesContext - * @param image The local image path from the web folder with leading slash '/' - * @param width Width in pixels - * @param height Height in pixels - * @param alt Optional alt/title text - * @param onclick JavaScript onclick event handler code - * @param verticalAlign Optional HTML alignment value - * @param style Optional inline CSS styling - * - * @return Populated img tag - */ - public static String buildImageTag(FacesContext context, String image, int width, int height, - String alt, String onclick, String verticalAlign, String style) - { - StringBuilder buf = new StringBuilder(200); - - style = style != null ? "border-width:0px; " + style : "border-width:0px;"; - buf.append("Utils.encode(alt);"); - - return buf.toString(); - } - - /** - * Build a context path safe image tag for the supplied image path. - * Image path should be supplied with a leading slash '/'. - * - * @param context FacesContext - * @param image The local image path from the web folder with leading slash '/' - * @param width Width in pixels - * @param height Height in pixels - * @param alt Optional alt/title text - * - * @return Populated img tag - */ - public static String buildImageTag(FacesContext context, String image, int width, int height, String alt) - { - return buildImageTag(context, image, width, height, alt, null); - } - - /** - * Build a context path safe image tag for the supplied image path. - * Image path should be supplied with a leading slash '/'. - * - * @param context FacesContext - * @param image The local image path from the web folder with leading slash '/' - * @param alt Optional alt/title text - * - * @return Populated img tag - */ - public static String buildImageTag(FacesContext context, String image, String alt) - { - return buildImageTag(context, image, alt, null); - } - - /** - * Build a context path safe image tag for the supplied image path. - * Image path should be supplied with a leading slash '/'. - * - * @param context FacesContext - * @param image The local image path from the web folder with leading slash '/' - * @param alt Optional alt/title text - * @param verticalAlign Optional HTML alignment value - * - * @return Populated img tag - */ - public static String buildImageTag(FacesContext context, String image, String alt, String verticalAlign) - { - StringBuilder buf = new StringBuilder(128); - buf.append("Utils.encode(alt);"); - - return buf.toString(); - } - - /** - * Return the parent UIForm component for the specified UIComponent - * - * @param context FaceContext - * @param component The UIComponent to find parent Form for - * - * @return UIForm parent or null if none found in hiearachy - */ - public static UIForm getParentForm(FacesContext context, UIComponent component) - { - UIComponent parent = component.getParent(); - while (parent != null) - { - if (parent instanceof UIForm) - { - break; - } - parent = parent.getParent(); - } - return (UIForm)parent; - } - - /** - * Return the parent UIComponent implementing the NamingContainer interface for - * the specified UIComponent. - * - * @param context FaceContext - * @param component The UIComponent to find parent Form for - * - * @return NamingContainer parent or null if none found in hiearachy - */ - public static UIComponent getParentNamingContainer(FacesContext context, UIComponent component) - { - UIComponent parent = component.getParent(); - while (parent != null) - { - if (parent instanceof NamingContainer) - { - break; - } - parent = parent.getParent(); - } - return (UIComponent)parent; - } - - /** - * Return the parent UIComponent implementing the IDataContainer interface for - * the specified UIComponent. - * - * @param context FaceContext - * @param component The UIComponent to find parent IDataContainer for - * - * @return IDataContainer parent or null if none found in hiearachy - */ - public static IDataContainer getParentDataContainer(FacesContext context, UIComponent component) - { - UIComponent parent = component.getParent(); - while (parent != null) - { - if (parent instanceof IDataContainer) - { - break; - } - parent = parent.getParent(); - } - return (IDataContainer)parent; - } - - /** - * Determines whether the given component is disabled or readonly - * - * @param component The component to test - * @return true if the component is either disabled or set to readonly - */ - public static boolean isComponentDisabledOrReadOnly(UIComponent component) - { - boolean disabled = false; - boolean readOnly = false; - - Object disabledAttr = component.getAttributes().get("disabled"); - if (disabledAttr != null) - { - disabled = disabledAttr.equals(Boolean.TRUE); - } - - if (disabled == false) - { - Object readOnlyAttr = component.getAttributes().get("readonly"); - if (readOnlyAttr != null) - { - readOnly = readOnlyAttr.equals(Boolean.TRUE); - } - } - - return disabled || readOnly; - } - - /** - * Invoke the method encapsulated by the supplied MethodBinding - * - * @param context FacesContext - * @param method MethodBinding to invoke - * @param event ActionEvent to pass to the method of signature: - * public void myMethodName(ActionEvent event) - */ - public static void processActionMethod(FacesContext context, MethodBinding method, ActionEvent event) - { - try - { - method.invoke(context, new Object[] {event}); - } - catch (EvaluationException e) - { - Throwable cause = e.getCause(); - if (cause instanceof AbortProcessingException) - { - throw (AbortProcessingException)cause; - } - else - { - throw e; - } - } - } - - /** - * Adds a global error message - * - * @param msg The error message - */ - public static void addErrorMessage(String msg) - { - addErrorMessage(msg, null); - } - - /** - * Adds a global error message and logs exception details - * - * @param msg The error message - * @param err The exception to log - */ - public static void addErrorMessage(String msg, Throwable err) - { - FacesContext context = FacesContext.getCurrentInstance( ); - FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg); - context.addMessage(null, facesMsg); - if (err != null) - { - if ((err instanceof InvalidNodeRefException == false && - err instanceof AccessDeniedException == false && - err instanceof NoTransformerException == false) || logger.isDebugEnabled()) - { - logger.error(msg, err); - } - } - } - - /** - * Adds a global status message that will be displayed by a Status Message UI component - * - * @param severity Severity of the message - * @param msg Text of the message - */ - public static void addStatusMessage(FacesMessage.Severity severity, String msg) - { - FacesContext fc = FacesContext.getCurrentInstance(); - String time = getTimeFormat(fc).format(new Date(System.currentTimeMillis())); - FacesMessage fm = new FacesMessage(severity, time, msg); - fc.addMessage(UIStatusMessage.STATUS_MESSAGE, fm); - } - - /** - * @return the formatter for locale sensitive Time formatting - */ - public static DateFormat getTimeFormat(FacesContext fc) - { - return getDateFormatFromPattern(fc, Application.getMessage(fc, MSG_TIME_PATTERN)); - } - - /** - * @return the formatter for locale sensitive Date formatting - */ - public static DateFormat getDateFormat(FacesContext fc) - { - return getDateFormatFromPattern(fc, Application.getMessage(fc, MSG_DATE_PATTERN)); - } - - /** - * @return the formatter for locale sensitive Date & Time formatting - */ - public static DateFormat getDateTimeFormat(FacesContext fc) - { - return getDateFormatFromPattern(fc, Application.getMessage(fc, MSG_DATE_TIME_PATTERN)); - } - - /** - * @return DataFormat object for the specified pattern - */ - private static DateFormat getDateFormatFromPattern(FacesContext fc, String pattern) - { - if (pattern == null) - { - throw new IllegalArgumentException("DateTime pattern is mandatory."); - } - try - { - return new SimpleDateFormat(pattern, Application.getLanguage(fc)); - } - catch (IllegalArgumentException err) - { - throw new AlfrescoRuntimeException("Invalid DateTime pattern", err); - } - } - - /** - * Parse XML format date YYYY-MM-DDTHH:MM:SS - * @param isoDate String - * @return Date or null if failed to parse - */ - public static Date parseXMLDateFormat(String isoDate) - { - Date parsed = null; - - try - { - int offset = 0; - - // extract year - int year = Integer.parseInt(isoDate.substring(offset, offset += 4)); - if (isoDate.charAt(offset) != '-') - { - throw new IndexOutOfBoundsException("Expected - character but found " + isoDate.charAt(offset)); - } - - // extract month - int month = Integer.parseInt(isoDate.substring(offset += 1, offset += 2)); - if (isoDate.charAt(offset) != '-') - { - throw new IndexOutOfBoundsException("Expected - character but found " + isoDate.charAt(offset)); - } - - // extract day - int day = Integer.parseInt(isoDate.substring(offset += 1, offset += 2)); - if (isoDate.charAt(offset) != 'T') - { - throw new IndexOutOfBoundsException("Expected T character but found " + isoDate.charAt(offset)); - } - - // extract hours, minutes, seconds and milliseconds - int hour = Integer.parseInt(isoDate.substring(offset += 1, offset += 2)); - if (isoDate.charAt(offset) != ':') - { - throw new IndexOutOfBoundsException("Expected : character but found " + isoDate.charAt(offset)); - } - int minutes = Integer.parseInt(isoDate.substring(offset += 1, offset += 2)); - if (isoDate.charAt(offset) != ':') - { - throw new IndexOutOfBoundsException("Expected : character but found " + isoDate.charAt(offset)); - } - int seconds = Integer.parseInt(isoDate.substring(offset += 1 , offset += 2)); - - // initialize Calendar object - Calendar calendar = Calendar.getInstance(); - calendar.setLenient(false); - calendar.set(Calendar.YEAR, year); - calendar.set(Calendar.MONTH, month - 1); - calendar.set(Calendar.DAY_OF_MONTH, day); - calendar.set(Calendar.HOUR_OF_DAY, hour); - calendar.set(Calendar.MINUTE, minutes); - calendar.set(Calendar.SECOND, seconds); - - // extract the date - parsed = calendar.getTime(); - } - catch(IndexOutOfBoundsException e) - { - } - catch(NumberFormatException e) - { - } - catch(IllegalArgumentException e) - { - } - - return parsed; - } - - - - /** - * Given a ConfigElement instance retrieve the display label, this could be - * dervied from a message bundle key or a literal string - * - * @param context FacesContext - * @param configElement The ConfigElement to test - * @return The resolved display label - */ - public static String getDisplayLabel(FacesContext context, ConfigElement configElement) - { - String label = null; - - // look for a localized string - String msgId = configElement.getAttribute("display-label-id"); - if (msgId != null) - { - label = Application.getMessage(context, msgId); - } - - // if there wasn't an externalized string look for a literal string - if (label == null) - { - label = configElement.getAttribute("display-label"); - } - - return label; - } - - /** - * Given a ConfigElement instance retrieve the description, this could be - * dervied from a message bundle key or a literal string - * - * @param context FacesContext - * @param configElement The ConfigElement to test - * @return The resolved description - */ - public static String getDescription(FacesContext context, ConfigElement configElement) - { - String description = null; - - // look for a localized string - String msgId = configElement.getAttribute("description-id"); - if (msgId != null) - { - description = Application.getMessage(context, msgId); - } - - // if there wasn't an externalized string look for a literal string - if (description == null) - { - description = configElement.getAttribute("description"); - } - - return description; - } - - /** - * @return the browser User-Agent header value trimmed to either "Firefox" or "MSIE" as appropriate. - */ - public static String getUserAgent(FacesContext context) - { - Object userAgent = context.getExternalContext().getRequestHeaderMap().get("User-Agent"); - if (userAgent != null) - { - if (userAgent.toString().indexOf("Firefox/") != -1) - { - return USER_AGENT_FIREFOX; - } - else if (userAgent.toString().indexOf("MSIE") != -1) - { - return USER_AGENT_MSIE; - } - else - { - return userAgent.toString(); - } - } - return ""; - } - - /** - * Generate the QName sort for a standard Person lookup. The filter is - * standardised across multiple JSF components and beans, and used with - * {@link PersonService#getPeople(List, boolean, List, org.alfresco.query.PagingRequest)} - */ - public static List> generatePersonSort() - { - List> sort = new ArrayList>(); - sort.add(new Pair(ContentModel.PROP_FIRSTNAME, true)); - sort.add(new Pair(ContentModel.PROP_LASTNAME, true)); - sort.add(new Pair(ContentModel.PROP_USERNAME, true)); - return sort; - } - - /** - * Generate the QName filter for a standard Person lookup. The filter is - * standardised across multiple JSF components and beans, and used with - * {@link PersonService#getPeople(List, boolean, List, org.alfresco.query.PagingRequest)} - * - * @param term Search term - */ - public static List> generatePersonFilter(String term) - { - List> filter = new ArrayList>(); - filter.add(new Pair(ContentModel.PROP_FIRSTNAME, term)); - filter.add(new Pair(ContentModel.PROP_LASTNAME, term)); - filter.add(new Pair(ContentModel.PROP_USERNAME, term)); - - // In order to support queries for "Alan Smithee", we'll parse these tokens - // and add them in to the query. - Pair tokenisedName = tokeniseName(term); - if (tokenisedName != null) - { - filter.add(new Pair(ContentModel.PROP_FIRSTNAME, tokenisedName.getFirst())); - filter.add(new Pair(ContentModel.PROP_LASTNAME, tokenisedName.getSecond())); - } - - return filter; - } - - /** - * This method will tokenise a name string in order to extract first name, last name - if possible. - * The split is simple - it's made on the first whitespace within the trimmed nameFilter String. So - *

- * "Luke Skywalker" becomes ["Luke", "Skywalker"]. - *

- * "Jar Jar Binks" becomes ["Jar", "Jar Binks"]. - *

- * "C-3PO" becomes null. - * - * @param nameFilter String - * @return A Pair if the String is valid, else null. - */ - private static Pair tokeniseName(String nameFilter) - { - Pair result = null; - - if (nameFilter != null) - { - final String trimmedNameFilter = nameFilter.trim(); - - // We can only have a first name and a last name if we have at least 3 characters e.g. "A B". - if (trimmedNameFilter.length() > 3) - { - final String[] tokens = trimmedNameFilter.split(ON_FIRST_SPACE, 2); - if (tokens.length == 2) - { - result = new Pair(tokens[0], tokens[1]); - } - } - } - - return result; - } - - /** - * How many results should a person search return up to? This is needed - * because the JSF components do paging differently. - * For now, hard coded at 1000, may be configurable later - */ - public static int getPersonMaxResults() - { - return 1000; - } - - /** - * Generate the Lucene query for a standard Person search. The query used is standardised - * across multiple JSF components and beans. - * - * @param query Buffer for the query - * @param term Search term - * @deprecated Use {@link #generatePersonFilter(String)} and {@link PersonService#getPeople(List, boolean, List, org.alfresco.query.PagingRequest)} instead - */ - public static void generatePersonSearch(StringBuilder query, String term) - { - // define the query to find people by their first or last name - for (StringTokenizer t = new StringTokenizer(term.trim(), " "); t.hasMoreTokens(); /**/) - { - String token = SearchLanguageConversion.escapeLuceneQuery(t.nextToken()); - query.append("+TYPE:\"").append(ContentModel.TYPE_PERSON).append("\" "); - query.append("+(@").append(NamespaceService.CONTENT_MODEL_PREFIX).append("\\:firstName:\"*"); - query.append(token); - query.append("*\" @").append(NamespaceService.CONTENT_MODEL_PREFIX).append("\\:lastName:\"*"); - query.append(token); - query.append("*\" @").append(NamespaceService.CONTENT_MODEL_PREFIX).append("\\:userName:"); - query.append(token); - query.append("*) "); - } - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/WebResources.java b/war/src/main/java/org/alfresco/web/ui/common/WebResources.java deleted file mode 100644 index cf3041f9b4..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/WebResources.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common; - -/** - * Class containing well known web resource paths for images etc. - * - * @author Kevin Roast - */ -public class WebResources -{ - // Image paths - public static final String IMAGE_PREVIOUSPAGE_NONE = "/images/icons/PreviousPage_unavailable.gif"; - public static final String IMAGE_PREVIOUSPAGE = "/images/icons/PreviousPage.gif"; - public static final String IMAGE_FIRSTPAGE_NONE = "/images/icons/FirstPage_unavailable.gif"; - public static final String IMAGE_FIRSTPAGE = "/images/icons/FirstPage.gif"; - public static final String IMAGE_NEXTPAGE_NONE = "/images/icons/NextPage_unavailable.gif"; - public static final String IMAGE_NEXTPAGE = "/images/icons/NextPage.gif"; - public static final String IMAGE_LASTPAGE_NONE = "/images/icons/LastPage_unavailable.gif"; - public static final String IMAGE_LASTPAGE = "/images/icons/LastPage.gif"; - - public static final String IMAGE_SORTUP = "/images/icons/sort_up.gif"; - public static final String IMAGE_SORTDOWN = "/images/icons/sort_down.gif"; - public static final String IMAGE_SORTNONE = "/images/icons/sort_flat.gif"; - - public static final String IMAGE_EXPANDED = "/images/icons/expanded.gif"; - public static final String IMAGE_COLLAPSED = "/images/icons/collapsed.gif"; - - public static final String IMAGE_MOVELEFT = "/images/icons/move_left.gif"; - public static final String IMAGE_MOVERIGHT = "/images/icons/move_right.gif"; - public static final String IMAGE_GO_UP = "/images/icons/up.gif"; - - public static final String IMAGE_INFO = "/images/icons/info_icon.gif"; -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/IBreadcrumbHandler.java b/war/src/main/java/org/alfresco/web/ui/common/component/IBreadcrumbHandler.java deleted file mode 100644 index e5f69eda54..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/IBreadcrumbHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component; - -import java.io.Serializable; - -/** - * @author Kevin Roast - */ -public interface IBreadcrumbHandler extends Serializable -{ - /** - * Override Object.toString() - * - * @return the element display label for this handler instance. - */ - public String toString(); - - /** - * Perform appropriate processing logic and then return a JSF navigation outcome. - * This method will be called by the framework when the handler instance is selected by the user. - * - * @param breadcrumb The UIBreadcrumb component that caused the navigation - * - * @return JSF navigation outcome - */ - public String navigationOutcome(UIBreadcrumb breadcrumb); -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/UIActionLink.java b/war/src/main/java/org/alfresco/web/ui/common/component/UIActionLink.java deleted file mode 100644 index 0434531cfa..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/UIActionLink.java +++ /dev/null @@ -1,362 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component; - -import java.util.HashMap; -import java.util.Map; - -import javax.faces.component.UICommand; -import javax.faces.context.FacesContext; -import javax.faces.el.ValueBinding; - -/** - * @author kevinr - */ -public class UIActionLink extends UICommand -{ - // ------------------------------------------------------------------------------ - // Construction - - /** - * Default Constructor - */ - public UIActionLink() - { - setRendererType("org.alfresco.faces.ActionLinkRenderer"); - } - - - // ------------------------------------------------------------------------------ - // Component implementation - - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.Controls"; - } - - /** - * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object) - */ - public void restoreState(FacesContext context, Object state) - { - Object values[] = (Object[])state; - // standard component attributes are restored by the super class - super.restoreState(context, values[0]); - this.padding = (Integer)values[1]; - this.image = (String)values[2]; - this.showLink = (Boolean)values[3]; - this.href = (String)values[4]; - this.tooltip = (String)values[5]; - this.target = (String)values[6]; - this.verticalAlign = (String)values[7]; - this.onclick = (String)values[8]; - } - - /** - * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext) - */ - public Object saveState(FacesContext context) - { - // standard component attributes are saved by the super class - return new Object[] - { - super.saveState(context), - this.padding, - this.image, - this.showLink, - this.href, - this.tooltip, - this.target, - this.verticalAlign, - this.onclick - }; - } - - - // ------------------------------------------------------------------------------ - // Strongly typed component property accessors - - /** - * Return the current child parameter map for this action link instance. - * This map is filled with name/value pairs from any child UIParameter components. - * - * @return Map of name/value pairs - */ - public Map getParameterMap() - { - if (this.params == null) - { - this.params = new HashMap(1, 1.0f); - } - return this.params; - } - - /** - * Get whether to show the link as well as the image if specified - * - * @return true to show the link as well as the image if specified - */ - public boolean getShowLink() - { - ValueBinding vb = getValueBinding("showLink"); - if (vb != null) - { - this.showLink = (Boolean)vb.getValue(getFacesContext()); - } - - if (this.showLink != null) - { - return this.showLink.booleanValue(); - } - else - { - // return default - return true; - } - } - - /** - * Set whether to show the link as well as the image if specified - * - * @param showLink Whether to show the link as well as the image if specified - */ - public void setShowLink(boolean showLink) - { - this.showLink = Boolean.valueOf(showLink); - } - - /** - * Get the padding value for rendering this component in a table. - * - * @return the padding in pixels, if set != 0 then a table will be rendering around the items - */ - public int getPadding() - { - ValueBinding vb = getValueBinding("padding"); - if (vb != null) - { - this.padding = (Integer)vb.getValue(getFacesContext()); - } - - return this.padding != null ? this.padding.intValue() : 0; - } - - /** - * Set the padding value for rendering this component in a table. - * - * @param padding value in pixels, if set != 0 then a table will be rendering around the items - */ - public void setPadding(int padding) - { - this.padding = padding; - } - - /** - * Return the Image path to use for this actionlink. - * If an image is specified, it is shown in additon to the value text unless - * the 'showLink' property is set to 'false'. - * - * @return the image path to display - */ - public String getImage() - { - ValueBinding vb = getValueBinding("image"); - if (vb != null) - { - this.image = (String)vb.getValue(getFacesContext()); - } - - return this.image; - } - - /** - * Set the Image path to use for this actionlink. - * If an image is specified, it is shown in additon to the value text unless - * the 'showLink' property is set to 'false'. - * - * @param image Image path to display - */ - public void setImage(String image) - { - this.image = image; - } - - /** - * @return Returns the href. - */ - public String getHref() - { - ValueBinding vb = getValueBinding("href"); - if (vb != null) - { - this.href = (String)vb.getValue(getFacesContext()); - } - - return this.href; - } - - /** - * @param href The href to set. - */ - public void setHref(String href) - { - this.href = href; - } - - /** - * Get the tooltip title text - * - * @return the tooltip - */ - public String getTooltip() - { - ValueBinding vb = getValueBinding("tooltip"); - if (vb != null) - { - this.tooltip = (String)vb.getValue(getFacesContext()); - } - - return this.tooltip; - } - - /** - * Set the tooltip title text - * - * @param tooltip the tooltip - */ - public void setTooltip(String tooltip) - { - this.tooltip = tooltip; - } - - /** - * Get the target - * - * @return the target - */ - public String getTarget() - { - ValueBinding vb = getValueBinding("target"); - if (vb != null) - { - this.target = (String)vb.getValue(getFacesContext()); - } - - return this.target; - } - - /** - * Set the target - * - * @param target the target - */ - public void setTarget(String target) - { - this.target = target; - } - - /** - * @return the verticalAlign - */ - public String getVerticalAlign() - { - ValueBinding vb = getValueBinding("verticalAlign"); - if (vb != null) - { - this.verticalAlign = (String)vb.getValue(getFacesContext()); - } - - return this.verticalAlign; - } - - /** - * @param verticalAlign the verticalAlign to set - */ - public void setVerticalAlign(String verticalAlign) - { - this.verticalAlign = verticalAlign; - } - - /** - * Returns the onclick handler - * - * @return The onclick handler - */ - public String getOnclick() - { - ValueBinding vb = getValueBinding("onclick"); - if (vb != null) - { - this.onclick = (String)vb.getValue(getFacesContext()); - } - - return this.onclick; - } - - /** - * Sets the onclick handler - * - * @param onclick The onclick handler - */ - public void setOnclick(String onclick) - { - this.onclick = onclick; - } - - - // ------------------------------------------------------------------------------ - // Private data - - /** the padding value in pixels, if set != 0 then a table will be rendered around the items */ - private Integer padding = null; - - /** True to show the link as well as the image if specified */ - private Boolean showLink = null; - - /** If an image is specified, it is shown in additon to the value text */ - private String image = null; - - /** static href to use instead of an action/actionlistener */ - private String href = null; - - /** tooltip title text to display on the action link */ - private String tooltip = null; - - /** the target reference */ - private String target = null; - - /** the onclick handler */ - private String onclick = null; - - /** the vertical alignment value */ - private String verticalAlign = null; - - /** Transient map of currently set param name/values pairs */ - private Map params = null; -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/UIBreadcrumb.java b/war/src/main/java/org/alfresco/web/ui/common/component/UIBreadcrumb.java deleted file mode 100644 index eaabf022da..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/UIBreadcrumb.java +++ /dev/null @@ -1,318 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component; - -import java.util.ArrayList; -import java.util.List; -import java.util.StringTokenizer; - -import javax.faces.component.UICommand; -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.el.ValueBinding; -import javax.faces.event.AbortProcessingException; -import javax.faces.event.ActionEvent; -import javax.faces.event.FacesEvent; - -/** - * @author kevinr - */ -public class UIBreadcrumb extends UICommand -{ - // ------------------------------------------------------------------------------ - // Construction - - /** - * Default Constructor - */ - public UIBreadcrumb() - { - setRendererType("org.alfresco.faces.BreadcrumbRenderer"); - } - - - // ------------------------------------------------------------------------------ - // Component implementation - - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.Controls"; - } - - /** - * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object) - */ - public void restoreState(FacesContext context, Object state) - { - Object values[] = (Object[])state; - // standard component attributes are restored by the super class - super.restoreState(context, values[0]); - this.separator = (String)values[1]; - this.showRoot = (Boolean)values[2]; - } - - /** - * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext) - */ - public Object saveState(FacesContext context) - { - Object values[] = new Object[3]; - // standard component attributes are saved by the super class - values[0] = super.saveState(context); - values[1] = this.separator; - values[2] = this.showRoot; - return (values); - } - - /** - * @see javax.faces.component.UICommand#broadcast(javax.faces.event.FacesEvent) - */ - public void broadcast(FacesEvent event) throws AbortProcessingException - { - if (event instanceof BreadcrumbEvent) - { - setSelectedPathIndex( ((BreadcrumbEvent)event).SelectedIndex ); - } - - // default ActionEvent processing for a UICommand - super.broadcast(event); - } - - /** - * Set the selected path index. This modifies the current path value. - */ - public void setSelectedPathIndex(int index) - { - // getValue() will return a List of IBreadcrumbHandler (see impl below) - List elements = (List)getValue(); - - if (elements.size() >= index) - { - // copy path elements up to the selected index to a new List - List path = new ArrayList(index + 1); - path.addAll(elements.subList(0, index + 1)); - - // set the new List as our new path value - setValue(path); - - // call the app logic for the element handler and perform any required navigation - String outcome = path.get(index).navigationOutcome(this); - if (outcome != null) - { - String viewId = getFacesContext().getViewRoot().getViewId(); - getFacesContext().getApplication().getNavigationHandler().handleNavigation( - getFacesContext(), viewId, outcome); - } - } - } - - /** - * Override getValue() to deal with converting a String path into a valid List of IBreadcrumbHandler - */ - public Object getValue() - { - List elements = null; - - Object value = super.getValue(); - if (value instanceof String) - { - elements = new ArrayList(8); - // found a String based path - convert to List of IBreadcrumbHandler instances - StringTokenizer t = new StringTokenizer((String)value, SEPARATOR); - while (t.hasMoreTokens() == true) - { - IBreadcrumbHandler handler = new DefaultPathHandler(t.nextToken()); - elements.add(handler); - } - - // save result so we don't need to repeat the conversion - setValue(elements); - } - else if (value instanceof List) - { - elements = (List)value; - } - else if (value != null) - { - throw new IllegalArgumentException("UIBreadcrumb value must be a String path or List of IBreadcrumbHandler!"); - } - else - { - elements = new ArrayList(8); - } - - return elements; - } - - /** - * Append a handler object to the current breadcrumb structure - * - * @param handler The IBreadcrumbHandler to append - */ - public void appendHandler(IBreadcrumbHandler handler) - { - if (handler == null) - { - throw new NullPointerException("IBreadcrumbHandler instance cannot be null!"); - } - - List elements = (List)getValue(); - elements.add(handler); - } - - - // ------------------------------------------------------------------------------ - // Strongly typed component property accessors - - /** - * Get the separator string to output between each breadcrumb element - * - * @return separator string - */ - public String getSeparator() - { - ValueBinding vb = getValueBinding("separator"); - if (vb != null) - { - this.separator = (String)vb.getValue(getFacesContext()); - } - - return this.separator; - } - - /** - * Set separator - * - * @param separator the separator string to output between each breadcrumb element - */ - public void setSeparator(String separator) - { - this.separator = separator; - } - - /** - * Get whether to show the root of the path - * - * @return true to show the root of the path, false to hide it - */ - public boolean getShowRoot() - { - ValueBinding vb = getValueBinding("showRoot"); - if (vb != null) - { - this.showRoot = (Boolean)vb.getValue(getFacesContext()); - } - - if (this.showRoot != null) - { - return this.showRoot.booleanValue(); - } - else - { - // return default - return true; - } - } - - /** - * Set whether to show the root of the path - * - * @param showRoot Whether to show the root of the path - */ - public void setShowRoot(boolean showRoot) - { - this.showRoot = Boolean.valueOf(showRoot); - } - - - // ------------------------------------------------------------------------------ - // Inner classes - - /** - * Class representing the clicking of a breadcrumb element. - */ - public static class BreadcrumbEvent extends ActionEvent - { - public BreadcrumbEvent(UIComponent component, int selectedIndex) - { - super(component); - SelectedIndex = selectedIndex; - } - - public int SelectedIndex = 0; - } - - /** - * Class representing a handler for the default String path based breadcrumb - */ - private static class DefaultPathHandler implements IBreadcrumbHandler - { - /** - * Constructor - * - * @param label The element display label - */ - public DefaultPathHandler(String label) - { - this.label = label; - } - - /** - * Return the element display label - */ - public String toString() - { - return this.label; - } - - /** - * @see org.alfresco.web.ui.common.component.IBreadcrumbHandler#navigationOutcome(org.alfresco.web.ui.common.component.UIBreadcrumb) - */ - public String navigationOutcome(UIBreadcrumb breadcrumb) - { - // no outcome for the default handler - return to current page - return null; - } - - private String label; - } - - - // ------------------------------------------------------------------------------ - // Private data - - /** visible separator value */ - private String separator = null; - - /** true to show the root of the breadcrumb path, false otherwise */ - private Boolean showRoot = null; - - /** the separator for a breadcrumb path value */ - public final static String SEPARATOR = "/"; -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/UIGenericPicker.java b/war/src/main/java/org/alfresco/web/ui/common/component/UIGenericPicker.java deleted file mode 100644 index 14b9e70412..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/UIGenericPicker.java +++ /dev/null @@ -1,729 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component; - -import java.io.IOException; -import java.text.MessageFormat; -import java.util.Map; -import java.util.ResourceBundle; - -import javax.faces.component.UICommand; -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; -import javax.faces.el.MethodBinding; -import javax.faces.el.ValueBinding; -import javax.faces.event.AbortProcessingException; -import javax.faces.event.ActionEvent; -import javax.faces.event.FacesEvent; -import javax.faces.model.SelectItem; - -import org.alfresco.web.app.Application; -import org.alfresco.web.ui.common.Utils; - -/** - * @author Kevin Roast - */ -public class UIGenericPicker extends UICommand -{ - /** action ids */ - private final static int ACTION_NONE = -1; - private final static int ACTION_SEARCH = 0; - private final static int ACTION_CLEAR = 1; - private final static int ACTION_FILTER = 2; - private final static int ACTION_ADD = 3; - - /** form field postfixes */ - private final static String FIELD_FILTER = "_filter"; - private final static String FIELD_CONTAINS = "_contains"; - private final static String FIELD_RESULTS = "_results"; - - /** I18N message strings */ - private final static String MSG_SEARCH = "search"; - private final static String MSG_CLEAR = "clear"; - private final static String MSG_ADD = "add"; - private final static String MSG_RESULTS1 = "results_contains"; - private final static String MSG_RESULTS2 = "results_contains_filter"; - - private final static int DEFAULT_HEIGHT = 100; - private final static int DEFAULT_WIDTH = 250; - - private MethodBinding queryCallback = null; - private Boolean showFilter = null; - private Boolean showContains = null; - private Boolean showAddButton = null; - private Boolean filterRefresh = null; - private Boolean multiSelect = null; - private String addButtonLabel = null; - private String searchButtonLabel = null; - private Integer width = null; - private Integer height = null; - - private SelectItem[] filters = null; - private int filterIndex = 0; - private String contains = ""; - private String[] selectedResults = null; - private SelectItem[] currentResults = null; - - - // ------------------------------------------------------------------------------ - // Component implementation - - /** - * Default constructor - */ - public UIGenericPicker() - { - setRendererType(null); - } - - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.GenericPicker"; - } - - /** - * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object) - */ - public void restoreState(FacesContext context, Object state) - { - Object values[] = (Object[])state; - // standard component attributes are restored by the super class - super.restoreState(context, values[0]); - showFilter = (Boolean)values[1]; - showContains = (Boolean)values[2]; - showAddButton = (Boolean)values[3]; - addButtonLabel = (String)values[4]; - width = (Integer)values[5]; - height = (Integer)values[6]; - filterIndex = (Integer)values[7]; - contains = (String)values[8]; - queryCallback = (MethodBinding) restoreAttachedState(context, values[9]); - selectedResults = (String[])values[10]; - currentResults = (SelectItem[])values[11]; - filters = (SelectItem[])values[12]; - filterRefresh = (Boolean)values[13]; - multiSelect = (Boolean)values[14]; - searchButtonLabel = (String)values[15]; - } - - /** - * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext) - */ - public Object saveState(FacesContext context) - { - Object values[] = new Object[16]; - // standard component attributes are saved by the super class - values[0] = super.saveState(context); - values[1] = showFilter; - values[2] = showContains; - values[3] = showAddButton; - values[4] = addButtonLabel; - values[5] = width; - values[6] = height; - values[7] = filterIndex; - values[8] = contains; - values[9] = saveAttachedState(context, queryCallback); - values[10] = selectedResults; - values[11] = currentResults; - values[12] = filters; - values[13] = filterRefresh; - values[14] = multiSelect; - values[15] = searchButtonLabel; - return (values); - } - - /** - * @see javax.faces.component.UIComponentBase#decode(javax.faces.context.FacesContext) - */ - public void decode(FacesContext context) - { - Map requestMap = context.getExternalContext().getRequestParameterMap(); - Map valuesMap = context.getExternalContext().getRequestParameterValuesMap(); - String fieldId = getHiddenFieldName(); - String value = (String)requestMap.get(fieldId); - - int action = ACTION_NONE; - if (value != null && value.length() != 0) - { - // decode the values - we are expecting an action identifier - action = Integer.parseInt(value); - } - - // we always process these values to keep the component up-to-date - - // now find the Filter drop-down value - int filterIndex = 0; - String strFilterIndex = (String)requestMap.get(fieldId + FIELD_FILTER); - if (strFilterIndex != null && strFilterIndex.length() != 0) - { - filterIndex = Integer.parseInt(strFilterIndex); - } - - // and the Contains text box value - String contains = (String)requestMap.get(fieldId + FIELD_CONTAINS); - - // and the Results selections - String[] results = (String[])valuesMap.get(fieldId + FIELD_RESULTS); - - // queue an event - PickerEvent event = new PickerEvent(this, action, filterIndex, contains, results); - queueEvent(event); - } - - /** - * @see javax.faces.component.UIComponentBase#broadcast(javax.faces.event.FacesEvent) - */ - public void broadcast(FacesEvent event) throws AbortProcessingException - { - if (event instanceof PickerEvent) - { - PickerEvent pickerEvent = (PickerEvent)event; - - // set component state from event properties - this.filterIndex = pickerEvent.FilterIndex; - this.contains = pickerEvent.Contains; - this.selectedResults = pickerEvent.Results; - - // delegate to appropriate action logic - switch (pickerEvent.Action) - { - case ACTION_ADD: - // call super for actionlistener execution - // it's up to the handler to get the results from the getSelectedResults() method - super.broadcast(event); - break; - - case ACTION_CLEAR: - this.contains = ""; - this.filterIndex = 0; - this.selectedResults = null; - this.currentResults = null; - break; - - case ACTION_FILTER: - // filter changed then query with new settings - case ACTION_SEARCH: - // query with current settings - MethodBinding callback = getQueryCallback(); - if (callback != null) - { - // use reflection to execute the query callback method and retrieve results - Object result = callback.invoke(getFacesContext(), new Object[] { - this.filterIndex, this.contains.trim()}); - - if (result instanceof SelectItem[]) - { - this.currentResults = (SelectItem[])result; - } - else - { - this.currentResults = null; - } - } - break; - } - } - else - { - super.broadcast(event); - } - } - - /** - * @see javax.faces.component.UIComponentBase#encodeBegin(javax.faces.context.FacesContext) - */ - public void encodeBegin(FacesContext context) throws IOException - { - if (isRendered() == false) - { - return; - } - - ResponseWriter out = context.getResponseWriter(); - - ResourceBundle bundle = Application.getBundle(context); - - String clientId = getClientId(context); - - // start outer table - out.write(""); - - // top row - out.write(""); - - // information row - if (this.currentResults != null && getShowContains() == true) - { - out.write(""); - } - - // results list row - out.write(""); - - // bottom row - add button - if (getShowAddButton() == true) - { - out.write(""); - } - - // end outer table - out.write("
"); - - // filter drop-down - if (getShowFilter() == true) - { - out.write(""); - } - out.write(""); - - // Contains textbox - if (getShowContains() == true) - { - out.write(" "); - } - - // Search button - out.write(""); - out.write("
"); - String resultsMsg; - if (getShowFilter() == false) - { - resultsMsg = MessageFormat.format(bundle.getString(MSG_RESULTS1), - new Object[] {Utils.encode(this.contains)}); - } - else - { - String filterMsg = this.filters[this.filterIndex].getLabel(); - resultsMsg = MessageFormat.format(bundle.getString(MSG_RESULTS2), - new Object[] {Utils.encode(this.contains), filterMsg}); - } - out.write(resultsMsg); - out.write(" "); - out.write(""); - out.write(Utils.encode(bundle.getString(MSG_CLEAR))); - out.write("
"); - out.write(""); - out.write("
"); - out.write(""); - out.write("
"); - } - - /** - * @return the filter options - */ - public SelectItem[] getFilterOptions() - { - if (this.filters == null) - { - ValueBinding vb = (ValueBinding)getValueBinding("filters"); - if (vb != null) - { - this.filters = (SelectItem[])vb.getValue(getFacesContext()); - } - } - - return this.filters; - } - - /** - * @return current filter drop-down selected index value - */ - public int getFilterIndex() - { - return this.filterIndex; - } - - /** - * @return Returns the searchButtonLabel. - */ - public String getSearchButtonLabel() - { - ValueBinding vb = getValueBinding("searchButtonLabel"); - if (vb != null) - { - this.searchButtonLabel = (String)vb.getValue(getFacesContext()); - } - - return this.searchButtonLabel; - } - - /** - * @param searchButtonLabel The searchButtonLabel to set. - */ - public void setSearchButtonLabel(String searchButtonLabel) - { - this.searchButtonLabel = searchButtonLabel; - } - - /** - * @return Returns the addButtonLabel. - */ - public String getAddButtonLabel() - { - ValueBinding vb = getValueBinding("addButtonLabel"); - if (vb != null) - { - this.addButtonLabel = (String)vb.getValue(getFacesContext()); - } - - return this.addButtonLabel; - } - - /** - * @param addButtonLabel The addButtonLabel to set. - */ - public void setAddButtonLabel(String addButtonLabel) - { - this.addButtonLabel = addButtonLabel; - } - - /** - * @return Returns the showAddButton. - */ - public boolean getShowAddButton() - { - ValueBinding vb = getValueBinding("showAddButton"); - if (vb != null) - { - this.showAddButton = (Boolean)vb.getValue(getFacesContext()); - } - - return showAddButton != null ? showAddButton.booleanValue() : true; - } - - /** - * @param showAddButton The showAddButton to set. - */ - public void setShowAddButton(boolean showAddButton) - { - this.showAddButton = Boolean.valueOf(showAddButton); - } - - /** - * @return Returns the showContains. - */ - public boolean getShowContains() - { - ValueBinding vb = getValueBinding("showContains"); - if (vb != null) - { - this.showContains = (Boolean)vb.getValue(getFacesContext()); - } - - return showContains != null ? showContains.booleanValue() : true; - } - - /** - * @param showContains The showContains to set. - */ - public void setShowContains(boolean showContains) - { - this.showContains = Boolean.valueOf(showContains); - } - - /** - * @return Returns the showFilter. - */ - public boolean getShowFilter() - { - ValueBinding vb = getValueBinding("showFilter"); - if (vb != null) - { - this.showFilter = (Boolean)vb.getValue(getFacesContext()); - } - - return showFilter != null ? showFilter.booleanValue() : true; - } - - /** - * @param showFilter The showFilter to set. - */ - public void setShowFilter(boolean showFilter) - { - this.showFilter = Boolean.valueOf(showFilter); - } - - /** - * @return Returns the filterRefresh. - */ - public boolean getFilterRefresh() - { - ValueBinding vb = getValueBinding("filterRefresh"); - if (vb != null) - { - this.filterRefresh = (Boolean)vb.getValue(getFacesContext()); - } - - return filterRefresh != null ? filterRefresh.booleanValue() : false; - } - - /** - * @param filterRefresh The filterRefresh to set. - */ - public void setFilterRefresh(boolean filterRefresh) - { - this.filterRefresh = Boolean.valueOf(filterRefresh); - } - - /** - * @return true if multi select should be enabled. - */ - public boolean getMultiSelect() - { - ValueBinding vb = getValueBinding("multiSelect"); - if (vb != null) - { - this.multiSelect = (Boolean)vb.getValue(getFacesContext()); - } - - return multiSelect != null ? multiSelect.booleanValue() : true; - } - - /** - * @param multiSelect Flag to determine whether multi select is enabled - */ - public void setMultiSelect(boolean multiSelect) - { - this.multiSelect = Boolean.valueOf(multiSelect); - } - - /** - * @return Returns the width. - */ - public int getWidth() - { - ValueBinding vb = getValueBinding("width"); - if (vb != null) - { - this.width = (Integer)vb.getValue(getFacesContext()); - } - - return width != null ? width.intValue() : DEFAULT_WIDTH; - } - - /** - * @param width The width to set. - */ - public void setWidth(int width) - { - this.width = Integer.valueOf(width); - } - - /** - * @return Returns the height. - */ - public int getHeight() - { - ValueBinding vb = getValueBinding("height"); - if (vb != null) - { - this.height = (Integer)vb.getValue(getFacesContext()); - } - - return height != null ? height.intValue() : DEFAULT_HEIGHT; - } - - /** - * @param height The height to set. - */ - public void setHeight(int height) - { - this.height = Integer.valueOf(height); - } - - /** - * @return Returns the queryCallback. - */ - public MethodBinding getQueryCallback() - { - return this.queryCallback; - } - - /** - * @param binding The queryCallback MethodBinding to set. - */ - public void setQueryCallback(MethodBinding binding) - { - this.queryCallback = binding; - } - - /** - * @return The selected results. An array of whatever string objects were attached to the - * SelectItem[] objects supplied as the result of the picker query. - */ - public String[] getSelectedResults() - { - return this.selectedResults; - } - - - // ------------------------------------------------------------------------------ - // Private helpers - - /** - * We use a hidden field per picker instance on the page. - * - * @return hidden field name - */ - private String getHiddenFieldName() - { - return getClientId(getFacesContext()); - } - - /** - * Generate FORM submit JavaScript for the specified action - * - * @param context FacesContext - * @param action Action index - * - * @return FORM submit JavaScript - */ - private String generateFormSubmit(FacesContext context, int action) - { - return Utils.generateFormSubmit(context, this, getHiddenFieldName(), Integer.toString(action)); - } - - - // ------------------------------------------------------------------------------ - // Inner classes - - /** - * Class representing the an action relevant to the Generic Selector component. - */ - @SuppressWarnings("serial") - public static class PickerEvent extends ActionEvent - { - public PickerEvent(UIComponent component, int action, int filterIndex, String contains, String[] results) - { - super(component); - Action = action; - FilterIndex = filterIndex; - Contains = contains; - Results = results; - } - - public int Action; - public int FilterIndex; - public String Contains; - public String[] Results; - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/UIImagePicker.java b/war/src/main/java/org/alfresco/web/ui/common/component/UIImagePicker.java deleted file mode 100644 index fbd503d97c..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/UIImagePicker.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component; - -import javax.faces.component.UIInput; -import javax.faces.context.FacesContext; - -/** - * Component to represent a selectable list of images - * - * @author gavinc - */ -public class UIImagePicker extends UIInput -{ - /** - * Default constructor - */ - public UIImagePicker() - { - // set the default renderer for an image picker component - setRendererType("org.alfresco.faces.Radio"); - } - - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.ImagePicker"; - } - - /** - * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object) - */ - public void restoreState(FacesContext context, Object state) - { - Object values[] = (Object[])state; - // standard component attributes are restored by the super class - super.restoreState(context, values[0]); - } - - /** - * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext) - */ - public Object saveState(FacesContext context) - { - Object values[] = new Object[1]; - // standard component attributes are saved by the super class - values[0] = super.saveState(context); - return (values); - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/UIListItem.java b/war/src/main/java/org/alfresco/web/ui/common/component/UIListItem.java deleted file mode 100644 index 87423099e6..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/UIListItem.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component; - -import java.io.Serializable; - -import javax.faces.context.FacesContext; -import javax.faces.el.ValueBinding; - -import org.springframework.extensions.webscripts.ui.common.component.SelfRenderingComponent; - -/** - * @author kevinr - */ -public class UIListItem extends SelfRenderingComponent implements Serializable -{ - // ------------------------------------------------------------------------------ - // Component Impl - - private static final long serialVersionUID = 6654796229844597265L; - - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.Controls"; - } - - /** - * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext) - */ - public Object saveState(FacesContext context) - { - Object values[] = new Object[7]; - values[0] = super.saveState(context); - values[1] = this.value; - values[2] = this.disabled; - values[3] = this.label; - values[4] = this.description; - values[5] = this.tooltip; - values[6] = this.image; - return ((Object) (values)); - } - - /** - * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object) - */ - public void restoreState(FacesContext context, Object state) - { - Object values[] = (Object[])state; - super.restoreState(context, values[0]); - this.value = values[1]; - this.disabled = (Boolean)values[2]; - this.label = (String)values[3]; - this.description = (String)values[4]; - this.tooltip = (String)values[5]; - this.image = (String)values[6]; - } - - - // ------------------------------------------------------------------------------ - // Strongly typed component property accessors - - /** - * Get the value - the value is used in a equals() match against the current value in the - * parent ModeList component to set the selected item. - * - * @return the value - */ - public Object getValue() - { - ValueBinding vb = getValueBinding("value"); - if (vb != null) - { - this.value = vb.getValue(getFacesContext()); - } - - return this.value; - } - - /** - * Set the value - the value is used in a equals() match against the current value in the - * parent ModeList component to set the selected item. - * - * @param value the value - */ - public void setValue(Object value) - { - this.value = value; - } - - /** - * Returns the disabled flag - * - * @return true if the mode list is disabled - */ - public boolean isDisabled() - { - ValueBinding vb = getValueBinding("disabled"); - if (vb != null) - { - this.disabled = (Boolean)vb.getValue(getFacesContext()); - } - - if (this.disabled != null) - { - return this.disabled.booleanValue(); - } - else - { - // return the default - return false; - } - } - - /** - * Sets whether the mode list is disabled - * - * @param disabled the disabled flag - */ - public void setDisabled(boolean disabled) - { - this.disabled = disabled; - } - - /** - * @return Returns the label. - */ - public String getLabel() - { - ValueBinding vb = getValueBinding("label"); - if (vb != null) - { - this.label = (String)vb.getValue(getFacesContext()); - } - - return this.label; - } - - /** - * @param label The label to set. - */ - public void setLabel(String label) - { - this.label = label; - } - - /** - * @return Returns the description. - */ - public String getDescription() - { - ValueBinding vb = getValueBinding("description"); - if (vb != null) - { - this.description = (String)vb.getValue(getFacesContext()); - } - - return this.description; - } - - /** - * @param description The description to set. - */ - public void setDescription(String description) - { - this.description = description; - } - - /** - * @return Returns the image. - */ - public String getImage() - { - ValueBinding vb = getValueBinding("image"); - if (vb != null) - { - this.image = (String)vb.getValue(getFacesContext()); - } - - return this.image; - } - - /** - * @param image The image to set. - */ - public void setImage(String image) - { - this.image = image; - } - - /** - * @return Returns the tooltip. - */ - public String getTooltip() - { - ValueBinding vb = getValueBinding("tooltip"); - if (vb != null) - { - this.tooltip = (String)vb.getValue(getFacesContext()); - } - - return this.tooltip; - } - - /** - * @param tooltip The tooltip to set. - */ - public void setTooltip(String tooltip) - { - this.tooltip = tooltip; - } - - - // ------------------------------------------------------------------------------ - // Private data - - /** the component value */ - private Object value = null; - - /** disabled flag */ - private Boolean disabled = null; - - /** the tooltip */ - private String tooltip; - - /** the label */ - private String label; - - /** the description */ - private String description; - - /** the image */ - private String image; -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/UIListItems.java b/war/src/main/java/org/alfresco/web/ui/common/component/UIListItems.java deleted file mode 100644 index fc668764d5..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/UIListItems.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component; - -import javax.faces.context.FacesContext; -import javax.faces.el.ValueBinding; - -import org.springframework.extensions.webscripts.ui.common.component.SelfRenderingComponent; - -/** - * Allows a group of UIListItem objects to be represented. - * - * @author gavinc - */ -public class UIListItems extends SelfRenderingComponent -{ - private Object value; - private boolean cacheValue; - - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.ListItems"; - } - - /** - * @return Returns the object holding the decriptions - */ - public Object getValue() - { - if (getCacheValue() == false || this.value == null) - { - ValueBinding vb = getValueBinding("value"); - if (vb != null) - { - this.value = vb.getValue(getFacesContext()); - } - } - return this.value; - } - - /** - * @param value Sets the object holding the description - */ - public void setValue(Object value) - { - this.value = value; - } - - /** - * @return the cacheValue - */ - public boolean getCacheValue() - { - ValueBinding vb = getValueBinding("cacheValue"); - if (vb != null) - { - this.cacheValue = (Boolean)vb.getValue(getFacesContext());; - } - return this.cacheValue; - } - - /** - * @param cacheValue the cacheValue to set - */ - public void setCacheValue(boolean cacheValue) - { - this.cacheValue = cacheValue; - } - - /** - * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object) - */ - public void restoreState(FacesContext context, Object state) - { - Object values[] = (Object[])state; - // standard component attributes are restored by the super class - super.restoreState(context, values[0]); - this.value = values[1]; - this.cacheValue = (Boolean)values[2]; - } - - /** - * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext) - */ - public Object saveState(FacesContext context) - { - // standard component attributes are saved by the super class - return new Object[] { - super.saveState(context), - this.value, - this.cacheValue - }; - } -} - diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/UIMenu.java b/war/src/main/java/org/alfresco/web/ui/common/component/UIMenu.java deleted file mode 100644 index 8733714033..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/UIMenu.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component; - -import java.io.IOException; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; -import javax.faces.el.ValueBinding; - -import org.alfresco.web.ui.common.Utils; -import org.springframework.extensions.webscripts.ui.common.component.SelfRenderingComponent; - -/** - * @author Kevin Roast - */ -public class UIMenu extends SelfRenderingComponent -{ - // ------------------------------------------------------------------------------ - // Component Impl - - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.Controls"; - } - - /** - * @see javax.faces.component.UIComponentBase#encodeBegin(javax.faces.context.FacesContext) - */ - public void encodeBegin(FacesContext context) throws IOException - { - if (!isRendered()) - { - return; - } - - ResponseWriter out = context.getResponseWriter(); - - // output a textual label with an optional icon to show the menu - String menuId = getNextMenuId(this, context); - out.write("'); - - // output label text - String label = getLabel(); - if (label != null) - { - out.write(Utils.encode(label)); - } - - // output image - if (getAttributes().get("image") != null) - { - out.write(Utils.buildImageTag(context, (String)getAttributes().get("image"), tooltip, "-4px")); - } - - out.write(""); - - // output the hidden DIV section to contain the menu item table - out.write("

"); - } - - /** - * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object) - */ - public void restoreState(FacesContext context, Object state) - { - Object values[] = (Object[])state; - // standard component attributes are restored by the super class - super.restoreState(context, values[0]); - this.label = (String)values[1]; - this.tooltip = (String)values[2]; - } - - /** - * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext) - */ - public Object saveState(FacesContext context) - { - return new Object[] { super.saveState(context), this.label, this.tooltip }; - } - - - // ------------------------------------------------------------------------------ - // Strongly typed component property accessors - - /** - * @return Returns the label. - */ - public String getLabel() - { - ValueBinding vb = getValueBinding("label"); - if (vb != null) - { - this.label = (String)vb.getValue(getFacesContext()); - } - return this.label; - } - - /** - * @param label The label to set. - */ - public void setLabel(String label) - { - this.label = label; - } - - /** - * @return Returns the tooltip. - */ - public String getTooltip() - { - ValueBinding vb = getValueBinding("tooltip"); - if (vb != null) - { - this.tooltip = (String)vb.getValue(getFacesContext()); - } - return this.tooltip; - } - - /** - * @param tooltip The tooltip to set. - */ - public void setTooltip(String tooltip) - { - this.tooltip = tooltip; - } - - - // ------------------------------------------------------------------------------ - // Helpers - - /** - * Return the next usable menu DIV id in a sequence - * - * @param context FacesContext - * - * @return next menu ID - */ - public static String getNextMenuId(UIComponent component, FacesContext context) - { - Integer val = (Integer)context.getExternalContext().getRequestMap().get(MENU_ID_KEY); - if (val == null) - { - val = Integer.valueOf(0); - } - - // build next id in sequence - String id = component.getClientId(context) + '_' + val.toString(); - - // save incremented value in the request ready for next menu component instance - val = Integer.valueOf( val.intValue() + 1 ); - context.getExternalContext().getRequestMap().put(MENU_ID_KEY, val); - - return id; - } - - - // ------------------------------------------------------------------------------ - // Private members - - private final static String MENU_ID_KEY = "__awc_menu_id"; - - private String label; - - private String tooltip; -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/UIModeList.java b/war/src/main/java/org/alfresco/web/ui/common/component/UIModeList.java deleted file mode 100644 index b5bcb52be2..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/UIModeList.java +++ /dev/null @@ -1,337 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component; - -import javax.faces.component.UICommand; -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.el.ValueBinding; -import javax.faces.event.AbortProcessingException; -import javax.faces.event.ActionEvent; -import javax.faces.event.FacesEvent; - -/** - * @author Kevin Roast - */ -public class UIModeList extends UICommand -{ - // ------------------------------------------------------------------------------ - // Construction - - /** - * Default constructor - */ - public UIModeList() - { - setRendererType("org.alfresco.faces.ModeListRenderer"); - } - - - // ------------------------------------------------------------------------------ - // Component Impl - - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.Controls"; - } - - /** - * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object) - */ - public void restoreState(FacesContext context, Object state) - { - Object values[] = (Object[])state; - // standard component attributes are restored by the super class - super.restoreState(context, values[0]); - this.iconColumnWidth = (Integer)values[1]; - this.horizontal = (Boolean)values[2]; - this.disabled = (Boolean)values[3]; - this.label = (String)values[4]; - this.menu = (Boolean)values[5]; - this.menuImage = (String)values[6]; - } - - /** - * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext) - */ - public Object saveState(FacesContext context) - { - Object values[] = new Object[7]; - // standard component attributes are saved by the super class - values[0] = super.saveState(context); - values[1] = this.iconColumnWidth; - values[2] = this.horizontal; - values[3] = this.disabled; - values[4] = this.label; - values[5] = this.menu; - values[6] = this.menuImage; - return (values); - } - - /** - * @see javax.faces.component.UICommand#broadcast(javax.faces.event.FacesEvent) - */ - public void broadcast(FacesEvent event) throws AbortProcessingException - { - if (event instanceof ModeListItemSelectedEvent) - { - // found an event for us, update the value for this component - setValue( ((ModeListItemSelectedEvent)event).SelectedValue ); - } - - // default ActionEvent processing for a UICommand - super.broadcast(event); - } - - - // ------------------------------------------------------------------------------ - // Strongly typed property accessors - - /** - * Get the horizontal rendering flag - * - * @return true for horizontal rendering, false otherwise - */ - public boolean isHorizontal() - { - ValueBinding vb = getValueBinding("horizontal"); - if (vb != null) - { - this.horizontal = (Boolean)vb.getValue(getFacesContext()); - } - - if (this.horizontal != null) - { - return this.horizontal.booleanValue(); - } - else - { - // return the default - return false; - } - } - - /** - * Set true for horizontal rendering, false otherwise - * - * @param horizontal the horizontal - */ - public void setHorizontal(boolean horizontal) - { - this.horizontal = horizontal; - } - - /** - * Get the icon column width - * - * @return the icon column width - */ - public int getIconColumnWidth() - { - ValueBinding vb = getValueBinding("iconColumnWidth"); - if (vb != null) - { - this.iconColumnWidth = (Integer)vb.getValue(getFacesContext()); - } - - if (this.iconColumnWidth != null) - { - return this.iconColumnWidth.intValue(); - } - else - { - // return the default - return 20; - } - } - - /** - * Set the icon column width - * - * @param iconColumnWidth the icon column width - */ - public void setIconColumnWidth(int iconColumnWidth) - { - this.iconColumnWidth = Integer.valueOf(iconColumnWidth); - } - - /** - * Returns the disabled flag - * - * @return true if the mode list is disabled - */ - public boolean isDisabled() - { - ValueBinding vb = getValueBinding("disabled"); - if (vb != null) - { - this.disabled = (Boolean)vb.getValue(getFacesContext()); - } - - if (this.disabled != null) - { - return this.disabled.booleanValue(); - } - else - { - // return the default - return false; - } - } - - /** - * Sets whether the mode list is disabled - * - * @param disabled the disabled flag - */ - public void setDisabled(boolean disabled) - { - this.disabled = disabled; - } - - /** - * Returns the menu rendering flag - * - * @return true if the menu rendering mode is to be used - */ - public boolean isMenu() - { - ValueBinding vb = getValueBinding("menu"); - if (vb != null) - { - this.menu = (Boolean)vb.getValue(getFacesContext()); - } - - if (this.menu != null) - { - return this.menu.booleanValue(); - } - else - { - // return the default - return false; - } - } - - /** - * Sets whether the mode list is a menu - * - * @param menu the menu flag - */ - public void setMenu(boolean menu) - { - this.menu = menu; - } - - /** - * @return Returns the label. - */ - public String getLabel() - { - ValueBinding vb = getValueBinding("label"); - if (vb != null) - { - this.label = (String)vb.getValue(getFacesContext()); - } - - return this.label; - } - - /** - * @param label The label to set. - */ - public void setLabel(String label) - { - this.label = label; - } - - /** - * @return Returns the menu image. - */ - public String getMenuImage() - { - ValueBinding vb = getValueBinding("menuImage"); - if (vb != null) - { - this.menuImage = (String)vb.getValue(getFacesContext()); - } - - return this.menuImage; - } - - /** - * @param menuImage The menu image to set. - */ - public void setMenuImage(String menuImage) - { - this.menuImage = menuImage; - } - - - // ------------------------------------------------------------------------------ - // Private data - - /** the icon column width */ - private Integer iconColumnWidth; - - /** true for horizontal rendering, false otherwise */ - private Boolean horizontal = null; - - /** disabled flag */ - private Boolean disabled = null; - - /** menu rendering flag */ - private Boolean menu = null; - - /** menu image to use */ - private String menuImage = null; - - /** the label */ - private String label; - - - // ------------------------------------------------------------------------------ - // Inner classes - - /** - * Class representing a change in selection for a ModeList component. - */ - public static class ModeListItemSelectedEvent extends ActionEvent - { - private static final long serialVersionUID = 3618135654274774322L; - - public ModeListItemSelectedEvent(UIComponent component, Object selectedValue) - { - super(component); - SelectedValue = selectedValue; - } - - public Object SelectedValue = null; - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/UIOutputText.java b/war/src/main/java/org/alfresco/web/ui/common/component/UIOutputText.java deleted file mode 100644 index 21eeb1c105..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/UIOutputText.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component; - -import java.io.IOException; - -import javax.faces.component.UIOutput; -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; -import javax.faces.convert.Converter; -import javax.faces.el.ValueBinding; - -import org.springframework.extensions.surf.util.URLEncoder; -import org.alfresco.web.ui.common.Utils; - -/** - * Component that simply renders text - * - * @author gavinc - */ -public class UIOutputText extends UIOutput -{ - private Boolean encodeForJavaScript = null; - - /** - * Default constructor - */ - public UIOutputText() - { - setRendererType(null); - } - - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.OutputText"; - } - - /** - * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object) - */ - public void restoreState(FacesContext context, Object state) - { - Object values[] = (Object[])state; - // standard component attributes are restored by the super class - super.restoreState(context, values[0]); - this.encodeForJavaScript = (Boolean)values[1]; - } - - /** - * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext) - */ - public Object saveState(FacesContext context) - { - Object values[] = new Object[3]; - // standard component attributes are saved by the super class - values[0] = super.saveState(context); - values[1] = this.encodeForJavaScript; - return values; - } - - /** - * Sets whether the text should be encoded for JavaScript consumption - * - * @param encodeForJavaScript true to escape text - */ - public void setEncodeForJavaScript(boolean encodeForJavaScript) - { - this.encodeForJavaScript = Boolean.valueOf(encodeForJavaScript); - } - - /** - * Returns whether the text is going to be encoded or not - * - * @return true if the text is going to be encoded - */ - public boolean isEncodeForJavaScript() - { - if (this.encodeForJavaScript == null) - { - ValueBinding vb = getValueBinding("encodeForJavaScript"); - if (vb != null) - { - this.encodeForJavaScript = (Boolean)vb.getValue(getFacesContext()); - } - - if (this.encodeForJavaScript == null) - { - this.encodeForJavaScript = Boolean.FALSE; - } - } - - return this.encodeForJavaScript.booleanValue(); - } - - /** - * @see javax.faces.component.UIComponentBase#encodeBegin(javax.faces.context.FacesContext) - */ - public void encodeBegin(FacesContext context) throws IOException - { - if (isRendered() == false) - { - return; - } - - Object value = getValue(); - if (value != null) - { - Converter converter = getConverter(); - if (converter != null) - { - value = converter.getAsString(context, this, value); - } - - ResponseWriter out = context.getResponseWriter(); - - if (isEncodeForJavaScript()) - { - out.write( URLEncoder.encode((String)getValue()) ); - } - else - { - String style = (String)getAttributes().get("style"); - String styleClass = (String)getAttributes().get("styleClass"); - if (style != null || styleClass != null) - { - out.write(""); - } - else - { - out.write(Utils.encode(value.toString())); - } - } - } - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/UIPanel.java b/war/src/main/java/org/alfresco/web/ui/common/component/UIPanel.java deleted file mode 100644 index 3e6774cc08..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/UIPanel.java +++ /dev/null @@ -1,656 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component; - -import java.io.IOException; -import java.util.Map; - -import javax.faces.component.NamingContainer; -import javax.faces.component.UICommand; -import javax.faces.component.UIComponent; -import javax.faces.component.UIForm; -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; -import javax.faces.el.MethodBinding; -import javax.faces.el.ValueBinding; -import javax.faces.event.AbortProcessingException; -import javax.faces.event.ActionEvent; -import javax.faces.event.FacesEvent; - -import org.alfresco.web.ui.common.PanelGenerator; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.WebResources; - -/** - * @author kevinr - */ -public class UIPanel extends UICommand -{ - // ------------------------------------------------------------------------------ - // Component Impl - - /** - * Default constructor - */ - public UIPanel() - { - setRendererType(null); - } - - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.Controls"; - } - - /** - * Return the UI Component to be displayed on the right of the panel title area - * - * @return UIComponent - */ - public UIComponent getTitleComponent() - { - UIComponent titleComponent = null; - - // attempt to find a component with the specified ID - String facetsId = getFacetsId(); - if (facetsId != null) - { - UIForm parent = Utils.getParentForm(FacesContext.getCurrentInstance(), this); - UIComponent facetsComponent = parent.findComponent(facetsId); - if (facetsComponent != null) - { - // get the 'title' facet from the component - titleComponent = facetsComponent.getFacet("title"); - } - } - - return titleComponent; - } - - /** - * @see javax.faces.component.UIComponentBase#encodeBegin(javax.faces.context.FacesContext) - */ - public void encodeBegin(FacesContext context) throws IOException - { - if (isRendered() == false) - { - return; - } - - ResponseWriter out = context.getResponseWriter(); - - // determine if we have a component on the header - UIComponent titleComponent = getTitleComponent(); - - // determine whether we have any adornments - String label = getLabel(); - if (label != null) - { - label = Utils.encode(label); - } - if (label != null || isProgressive() == true || titleComponent != null) - { - this.hasAdornments = true; - } - - // make sure we have a default background color for the content area - String bgcolor = getBgcolor(); - if (bgcolor == null) - { - bgcolor = PanelGenerator.BGCOLOR_WHITE; - } - - // determine if we have a bordered title area, note, we also need to have - // the content area border defined as well - if (getTitleBgcolor() != null && getTitleBorder() != null && - getBorder() != null && this.hasAdornments) - { - this.hasBorderedTitleArea = true; - } - - // output first part of border table - if (this.hasBorderedTitleArea) - { - PanelGenerator.generatePanelStart( - out, - context.getExternalContext().getRequestContextPath(), - getTitleBorder(), - getTitleBgcolor()); - } - else if (getBorder() != null) - { - PanelGenerator.generatePanelStart( - out, - context.getExternalContext().getRequestContextPath(), - getBorder(), - bgcolor); - } - - if (this.hasAdornments) - { - // start the containing table if we have any adornments - out.write(""); - } - - // render the title component if supplied - if (titleComponent != null) - { - out.write(""); - } - - if (this.hasAdornments) - { - out.write("
"); - } - - // output progressive disclosure icon in appropriate state - // TODO: manage state of this icon via component Id! - if (isProgressive() == true) - { - out.write(""); - - if (isExpanded() == true) - { - out.write(Utils.buildImageTag(context, WebResources.IMAGE_EXPANDED, 11, 11, getLabel())); - } - else - { - out.write(Utils.buildImageTag(context, WebResources.IMAGE_COLLAPSED, 11, 11, getLabel())); - } - - out.write("  "); - } - - // output textual label - if (label != null) - { - out.write("'); - - out.write(label); // already encoded above - - out.write(""); - } - - if (this.hasAdornments) - { - out.write(""); - Utils.encodeRecursive(context, titleComponent); - out.write("
"); - } - - // if we have the titled border area, output the middle section - if (this.hasBorderedTitleArea && isExpanded()) - { - if (getExpandedTitleBorder() != null) - { - PanelGenerator.generateExpandedTitledPanelMiddle( - out, - context.getExternalContext().getRequestContextPath(), - getTitleBorder(), - getExpandedTitleBorder(), - getBorder(), - getBgcolor()); - } - else - { - PanelGenerator.generateTitledPanelMiddle( - out, - context.getExternalContext().getRequestContextPath(), - getTitleBorder(), - getBorder(), - getBgcolor()); - } - } - } - - /** - * @see javax.faces.component.UIComponentBase#encodeEnd(javax.faces.context.FacesContext) - */ - public void encodeEnd(FacesContext context) throws IOException - { - if (isRendered() == false) - { - return; - } - - ResponseWriter out = context.getResponseWriter(); - - // output final part of border table - if (this.hasBorderedTitleArea && isExpanded() == false) - { - PanelGenerator.generatePanelEnd( - out, - context.getExternalContext().getRequestContextPath(), - getTitleBorder()); - } - else if (getBorder() != null) - { - PanelGenerator.generatePanelEnd( - out, - context.getExternalContext().getRequestContextPath(), - getBorder()); - } - } - - /** - * @see javax.faces.component.UIComponentBase#decode(javax.faces.context.FacesContext) - */ - public void decode(FacesContext context) - { - Map requestMap = context.getExternalContext().getRequestParameterMap(); - String fieldId = getHiddenFieldName(context); - String value = (String)requestMap.get(fieldId); - - // we encoded the value to start with our Id - if (value != null && value.startsWith(getClientId(context))) - { - // we were clicked, strip out the value - value = value.substring(getClientId(context).length() + 1); - - // the expand/collapse icon was clicked, so toggle the state - ExpandedEvent event = new ExpandedEvent(this, Boolean.parseBoolean(value)); - queueEvent(event); - - // - // TODO: See http://forums.java.sun.com/thread.jspa?threadID=524925&start=15&tstart=0 - // Bug/known issue in JSF 1.1 RI - // This causes a problem where the View attempts to assign duplicate Ids - // to components when createUniqueId() on UIViewRoot is called before the - // render phase. This occurs in the Panel tag as it must call getComponent() - // early to decide whether to allow the tag to render contents or not. - // - // context.getViewRoot().setTransient(true); - // - // The other solution is to explicity give ALL child components of the - // panel a unique Id rather than a generated one! - } - } - - /** - * @see javax.faces.component.UICommand#broadcast(javax.faces.event.FacesEvent) - */ - public void broadcast(FacesEvent event) throws AbortProcessingException - { - if (event instanceof ExpandedEvent) - { - // expanded event - we handle this - setExpanded( ((ExpandedEvent)event).State ); - - if (getExpandedActionListener() != null) - { - Utils.processActionMethod(getFacesContext(), getExpandedActionListener(), (ExpandedEvent)event); - } - } - else - { - super.broadcast(event); - } - } - - /** - * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object) - */ - public void restoreState(FacesContext context, Object state) - { - Object values[] = (Object[])state; - // standard component attributes are restored by the super class - super.restoreState(context, values[0]); - setExpanded( ((Boolean)values[1]).booleanValue() ); - this.progressive = (Boolean)values[2]; - this.border = (String)values[3]; - this.bgcolor = (String)values[4]; - this.label = (String)values[5]; - this.titleBgcolor = (String)values[6]; - this.titleBorder = (String)values[7]; - this.expandedTitleBorder = (String)values[8]; - this.expandedActionListener = (MethodBinding)restoreAttachedState(context, values[9]); - this.facetsId = (String)values[10]; - } - - /** - * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext) - */ - public Object saveState(FacesContext context) - { - Object values[] = new Object[] { - super.saveState(context), - (isExpanded() ? Boolean.TRUE : Boolean.FALSE), - this.progressive, - this.border, - this.bgcolor, - this.label, - this.titleBgcolor, - this.titleBorder, - this.expandedTitleBorder, - saveAttachedState(context, this.expandedActionListener), - this.facetsId}; - return values; - } - - - // ------------------------------------------------------------------------------ - // Strongly typed component property accessors - - /** - * @param binding The MethodBinding to call when expand/collapse is performed by the user. - */ - public void setExpandedActionListener(MethodBinding binding) - { - this.expandedActionListener = binding; - } - - /** - * @return The MethodBinding to call when expand/collapse is performed by the user. - */ - public MethodBinding getExpandedActionListener() - { - return this.expandedActionListener; - } - - /** - * @return Returns the bgcolor. - */ - public String getBgcolor() - { - ValueBinding vb = getValueBinding("bgcolor"); - if (vb != null) - { - this.bgcolor = (String)vb.getValue(getFacesContext()); - } - - return this.bgcolor; - } - - /** - * @param bgcolor The bgcolor to set. - */ - public void setBgcolor(String bgcolor) - { - this.bgcolor = bgcolor; - } - - /** - * @return Returns the border name. - */ - public String getBorder() - { - ValueBinding vb = getValueBinding("border"); - if (vb != null) - { - this.border = (String)vb.getValue(getFacesContext()); - } - - return this.border; - } - - /** - * @param border The border name to user. - */ - public void setBorder(String border) - { - this.border = border; - } - - /** - * @return Returns the bgcolor of the title area - */ - public String getTitleBgcolor() - { - ValueBinding vb = getValueBinding("titleBgcolor"); - if (vb != null) - { - this.titleBgcolor = (String)vb.getValue(getFacesContext()); - } - - return this.titleBgcolor; - } - - /** - * @param titleBgcolor Sets the bgcolor of the title area - */ - public void setTitleBgcolor(String titleBgcolor) - { - this.titleBgcolor = titleBgcolor; - } - - /** - * @return Returns the border style of the title area - */ - public String getTitleBorder() - { - ValueBinding vb = getValueBinding("titleBorder"); - if (vb != null) - { - this.titleBorder = (String)vb.getValue(getFacesContext()); - } - - return this.titleBorder; - } - - /** - * @param titleBorder Sets the border style of the title area - */ - public void setTitleBorder(String titleBorder) - { - this.titleBorder = titleBorder; - } - - /** - * @return Returns the border style of the expanded title area - */ - public String getExpandedTitleBorder() - { - ValueBinding vb = getValueBinding("expandedTitleBorder"); - if (vb != null) - { - this.expandedTitleBorder = (String)vb.getValue(getFacesContext()); - } - - return this.expandedTitleBorder; - } - - /** - * @param expandedTitleBorder Sets the border style of the expanded title area - */ - public void setExpandedTitleBorder(String expandedTitleBorder) - { - this.expandedTitleBorder = expandedTitleBorder; - } - - /** - * @return Returns the label. - */ - public String getLabel() - { - ValueBinding vb = getValueBinding("label"); - if (vb != null) - { - this.label = (String)vb.getValue(getFacesContext()); - } - - return this.label; - } - - /** - * @param label The label to set. - */ - public void setLabel(String label) - { - this.label = label; - } - - /** - * @return Returns the progressive display setting. - */ - public boolean isProgressive() - { - ValueBinding vb = getValueBinding("progressive"); - if (vb != null) - { - this.progressive = (Boolean)vb.getValue(getFacesContext()); - } - - if (this.progressive != null) - { - return this.progressive.booleanValue(); - } - else - { - // return default - return false; - } - } - - /** - * @param progressive The progressive display boolean to set. - */ - public void setProgressive(boolean progressive) - { - this.progressive = Boolean.valueOf(progressive); - } - - /** - * Returns whether the component show allow rendering of its child components. - */ - public boolean isExpanded() - { - ValueBinding vb = getValueBinding("expanded"); - if (vb != null) - { - this.expanded = (Boolean)vb.getValue(getFacesContext()); - } - - if (this.expanded != null) - { - return this.expanded.booleanValue(); - } - else - { - // return default - return true; - } - } - - /** - * Sets whether the component show allow rendering of its child components. - * For this component we change this value if the user indicates to change the - * hidden/visible state of the progressive panel. - */ - public void setExpanded(boolean expanded) - { - this.expanded = Boolean.valueOf(expanded); - } - - /** - * Get the facets component Id to use - * - * @return the facets component Id - */ - public String getFacetsId() - { - ValueBinding vb = getValueBinding("facets"); - if (vb != null) - { - this.facetsId = (String)vb.getValue(getFacesContext()); - } - - return this.facetsId; - } - - /** - * Set the facets component Id to use - * - * @param facets the facets component Id - */ - public void setFacetsId(String facets) - { - this.facetsId = facets; - } - - - // ------------------------------------------------------------------------------ - // Private helpers - - /** - * We use a hidden field name based on the parent form component Id and - * the string "panel" to give a hidden field name that can be shared by all panels - * within a single UIForm component. - * - * @return hidden field name - */ - private String getHiddenFieldName(FacesContext fc) - { - UIForm form = Utils.getParentForm(fc, this); - return form.getClientId(fc) + NamingContainer.SEPARATOR_CHAR + "panel"; - } - - - // ------------------------------------------------------------------------------ - // Private members - - // component settings - private String border = null; - private String bgcolor = null; - private String titleBorder = null; - private String titleBgcolor = null; - private String expandedTitleBorder = null; - private Boolean progressive = null; - private String label = null; - private String facetsId = null; - private MethodBinding expandedActionListener = null; - - // component state - private boolean hasAdornments = false; - private boolean hasBorderedTitleArea = false; - private Boolean expanded = Boolean.TRUE; - - - // ------------------------------------------------------------------------------ - // Inner classes - - /** - * Class representing the an action relevant when the panel is expanded or collapsed. - */ - public static class ExpandedEvent extends ActionEvent - { - public ExpandedEvent(UIComponent component, boolean state) - { - super(component); - State = state; - } - - public boolean State; - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/UISelectList.java b/war/src/main/java/org/alfresco/web/ui/common/component/UISelectList.java deleted file mode 100644 index 79ab7dfdc2..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/UISelectList.java +++ /dev/null @@ -1,668 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component; - -import java.io.IOException; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.faces.component.NamingContainer; -import javax.faces.component.UICommand; -import javax.faces.component.UIComponent; -import javax.faces.component.UIForm; -import javax.faces.component.UIInput; -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; -import javax.faces.el.ValueBinding; -import javax.faces.event.AbortProcessingException; -import javax.faces.event.FacesEvent; -import javax.faces.event.FacesListener; -import javax.faces.event.PhaseId; - -import org.alfresco.web.ui.common.Utils; - -/** - * The SelectList component displays a graphical list of items, each with a label and icon image. - * The list has three selection modes; single select (radio), multi-select (checkbox) and active - * selection mode (child action components). - * - * The value for the component is collection of UIListItem objects or a UIListItems instance. - * - * For passive single and multi-select modes, the selected value(s) can be retrieved from the component. - * For active selection mode, appropriate child components such as Command buttons or Action Links - * will be rendered for each item in the list, data-binding to the specified 'var' variable should be - * used to bind required params. It is then up to the developer to retrieve the selected item param - * from the actionListener of the appropriate child component. - * - * @author Kevin Roast - */ -public class UISelectList extends UIInput implements NamingContainer -{ - private Boolean multiSelect; - private Boolean activeSelect; - private int rowIndex = -1; - private int itemCount; - private String onchange = null; - private Boolean escapeItemLabel; - private Boolean escapeItemDescription; - - // ------------------------------------------------------------------------------ - // Component Impl - - /** - * Default constructor - */ - public UISelectList() - { - setRendererType(null); - } - - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.Controls"; - } - - /** - * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object) - */ - public void restoreState(FacesContext context, Object state) - { - Object values[] = (Object[])state; - // standard component attributes are restored by the super class - super.restoreState(context, values[0]); - this.multiSelect = (Boolean)values[1]; - this.activeSelect = (Boolean)values[2]; - this.itemCount = (Integer)values[3]; - this.onchange = (String)values[4]; - this.escapeItemLabel = (Boolean)values[5]; - this.escapeItemDescription = (Boolean)values[6]; - } - - /** - * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext) - */ - public Object saveState(FacesContext context) - { - return new Object[] - { - super.saveState(context), - this.multiSelect, - this.activeSelect, - this.itemCount, - this.onchange, - this.escapeItemLabel, - this.escapeItemDescription - }; - } - - /** - * @return the client Id for this naming container component - based on the current row context. - * This allows a single component rendered multiple times in a list to dynamically base - * their ID on the current row - so that the 'correct' component is decoded and event is - * queued with the current row value. - */ - @Override - public String getClientId(FacesContext context) - { - String clientId = super.getClientId(context); - int rowIndex = getRowIndex(); - return (rowIndex == -1 ? clientId : clientId + "_" + rowIndex); - } - - /** - * Override the processing of child component decodes - we set the current row context so any - * events queued by child components wrapped in FacesEventWrapper have current row value. - */ - @Override - public void processDecodes(FacesContext context) - { - if (!isRendered()) - { - return; - } - - setRowIndex(-1); - for (UIComponent child : (List)this.getChildren()) - { - if (child instanceof UIListItem == false && child instanceof UIListItems == false) - { - for (int i=0; i"); - } - - /** - * Render a list item in the appropriate selection mode - * - * @param context FacesContext - * @param out ResponseWriter - * @param item UIListItem representing the item to render - */ - private void renderItem(FacesContext context, ResponseWriter out, UIListItem item) - throws IOException - { - boolean activeSelect = isActiveSelect(); - boolean escapeLabel = getEscapeItemLabel(); - boolean escapeDescription = getEscapeItemDescription(); - - // begin the row, add tooltip if present - String tooltip = item.getTooltip(); - out.write(""); - - if (activeSelect == false) - { - // we are rendering passive select list, so either multi or single selection using - // checkboxes or radio button control respectively - boolean multiSelect = isMultiSelect(); - String id = getClientId(context); - String itemValue = item.getValue().toString(); - out.write(""); - } - - // optional 32x32 pixel icon - String icon = item.getImage(); - if (icon != null) - { - out.write(""); // give pixel space around edges - out.write(Utils.buildImageTag(context, icon, 32, 32, "")); - out.write(""); - } - - // label and description text - String label = item.getLabel(); - String description = item.getDescription(); - out.write("
"); - if (escapeLabel) - { - out.write(Utils.encode(label)); - } - else - { - out.write(label); - } - out.write("
"); - if (description != null) - { - out.write("
"); - if (escapeDescription) - { - out.write(Utils.encode(description)); - } - else - { - out.write(description); - } - out.write("
"); - } - out.write(""); - - if (activeSelect) - { - // we are rendering an active select list with child components next to each item - // get the child components and look for compatible Command objects - out.write("'); - for (Iterator i = getChildren().iterator(); i.hasNext(); /**/) - { - UIComponent child = (UIComponent)i.next(); - if (child instanceof UICommand) - { - out.write(""); - Utils.encodeRecursive(context, child); - out.write(""); - } - } - out.write(""); - } - } - - - // ------------------------------------------------------------------------------ - // Strongly typed property accessors - - /** - * @return current row index - */ - public int getRowIndex() - { - return this.rowIndex; - } - - /** - * Set the transient current row index. Setting this value causes all child components to - * have their ID values reset - so that cached clientID values are regenerated when next requested. - * - * @param rowIndex int - */ - public void setRowIndex(int rowIndex) - { - if (isActiveSelect()) - { - this.rowIndex = rowIndex; - for (UIComponent child : (List)this.getChildren()) - { - if (child instanceof UIListItem == false && child instanceof UIListItems == false) - { - // forces a reset of the clientId for the component - // This is then regenerated - relative to this naming container which itself uses the - // current row index as part of the Id. This is what facilities the correct component - // rendering submit script and then identified during the decode() phase. - child.setId(child.getId()); - } - } - } - } - - /** - * Get the multi-select rendering flag - * - * @return true for multi-select rendering, false otherwise - */ - public boolean isMultiSelect() - { - ValueBinding vb = getValueBinding("multiSelect"); - if (vb != null) - { - this.multiSelect = (Boolean)vb.getValue(getFacesContext()); - } - - return this.multiSelect != null ? this.multiSelect.booleanValue() : false; - } - - /** - * Set true for multi-select rendering, false otherwise - * - * @param multiSelect True for multi-select - */ - public void setMultiSelect(boolean multiSelect) - { - this.multiSelect = multiSelect; - } - - /** - * Get the active selection mode flag - * - * @return true for active selection mode, false otherwise - */ - public boolean isActiveSelect() - { - ValueBinding vb = getValueBinding("activeSelect"); - if (vb != null) - { - this.activeSelect = (Boolean)vb.getValue(getFacesContext()); - } - - return this.activeSelect != null ? this.activeSelect.booleanValue() : false; - } - - /** - * Set true for active selection mode, false otherwise - * - * @param activeSelect True for active selection - */ - public void setActiveSelect(boolean activeSelect) - { - this.activeSelect = activeSelect; - } - - /** - * Get the escape item label flag - * - * @return true if the items label should be escaped, false otherwise - */ - public boolean getEscapeItemLabel() - { - ValueBinding vb = getValueBinding("escapeItemLabel"); - if (vb != null) - { - this.escapeItemLabel = (Boolean)vb.getValue(getFacesContext()); - } - - return this.escapeItemLabel != null ? this.escapeItemLabel.booleanValue() : true; - } - - /** - * Set true to escape the items label, false otherwise - * - * @param escapeItemLabel true to escape the items label - */ - public void setEscapeItemLabel(boolean escapeItemLabel) - { - this.escapeItemLabel = escapeItemLabel; - } - - /** - * Get the escape item description flag - * - * @return true if the items description should be escaped, false otherwise - */ - public boolean getEscapeItemDescription() - { - ValueBinding vb = getValueBinding("escapeItemDescription"); - if (vb != null) - { - this.escapeItemDescription = (Boolean)vb.getValue(getFacesContext()); - } - - return this.escapeItemDescription != null ? this.escapeItemDescription.booleanValue() : true; - } - - /** - * Set true to escape the items description, false otherwise - * - * @param escapeItemDescription true to escape the items description - */ - public void setEscapeItemDescription(boolean escapeItemDescription) - { - this.escapeItemDescription = escapeItemDescription; - } - - /** - * We use a hidden field name based on the parent form component Id and - * the string "selectlist" to give a hidden field name that can be shared by all - * SelectList components within a single UIForm component. - * - * @return hidden field name - */ - private static String getHiddenFieldName(FacesContext context, UIComponent component) - { - UIForm form = Utils.getParentForm(context, component); - return form.getClientId(context) + NamingContainer.SEPARATOR_CHAR + "selectlist"; - } - - - /** - * Wrapper for a FacesEvent to hold current row value when the event was fired - */ - private static class FacesEventWrapper extends FacesEvent - { - private FacesEvent wrappedFacesEvent; - private int rowIndex; - - public FacesEventWrapper(FacesEvent facesEvent, int rowIndex, UISelectList redirectComponent) - { - super(redirectComponent); - wrappedFacesEvent = facesEvent; - this.rowIndex = rowIndex; - } - - public PhaseId getPhaseId() - { - return wrappedFacesEvent.getPhaseId(); - } - - public void setPhaseId(PhaseId phaseId) - { - wrappedFacesEvent.setPhaseId(phaseId); - } - - public void queue() - { - wrappedFacesEvent.queue(); - } - - public String toString() - { - return wrappedFacesEvent.toString(); - } - - public boolean isAppropriateListener(FacesListener faceslistener) - { - return wrappedFacesEvent.isAppropriateListener(faceslistener); - } - - public void processListener(FacesListener faceslistener) - { - wrappedFacesEvent.processListener(faceslistener); - } - - public FacesEvent getWrappedFacesEvent() - { - return wrappedFacesEvent; - } - - public int getRowIndex() - { - return rowIndex; - } - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/UIStatusMessage.java b/war/src/main/java/org/alfresco/web/ui/common/component/UIStatusMessage.java deleted file mode 100644 index b839ded93a..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/UIStatusMessage.java +++ /dev/null @@ -1,354 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component; - -import java.io.IOException; -import java.io.Serializable; -import java.util.Date; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import javax.faces.application.FacesMessage; -import javax.faces.component.NamingContainer; -import javax.faces.component.UIComponent; -import javax.faces.component.UIForm; -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; -import javax.faces.el.ValueBinding; -import javax.faces.event.AbortProcessingException; -import javax.faces.event.ActionEvent; -import javax.faces.event.FacesEvent; - -import org.alfresco.web.app.Application; -import org.alfresco.web.ui.common.PanelGenerator; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.WebResources; -import org.springframework.extensions.webscripts.ui.common.component.SelfRenderingComponent; - -/** - * @author Kevin Roast - */ -public class UIStatusMessage extends SelfRenderingComponent implements Serializable -{ - private static final long serialVersionUID = -575221861760604440L; - - - /** - * Default Constructor - */ - public UIStatusMessage() - { - setRendererType(null); - - // add default message to display - FacesContext fc = FacesContext.getCurrentInstance(); - String msg = Application.getMessage(fc, MSG_DEFAULT_STATUS); - String time = Utils.getTimeFormat(fc).format(new Date(System.currentTimeMillis())); - this.messages.add(new FacesMessage(FacesMessage.SEVERITY_INFO, time, msg)); - } - - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.StatusMessage"; - } - - /** - * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object) - */ - public void restoreState(FacesContext context, Object state) - { - Object values[] = (Object[])state; - // standard component attributes are restored by the super class - super.restoreState(context, values[0]); - this.border = (String)values[1]; - this.bgcolor = (String)values[2]; - this.messages = (List)values[3]; - this.currentMessage = ((Integer)values[4]).intValue(); - } - - /** - * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext) - */ - public Object saveState(FacesContext context) - { - return new Object[] - { - super.saveState(context), - this.border, - this.bgcolor, - this.messages, - Integer.valueOf(this.currentMessage) - }; - } - - /** - * @see javax.faces.component.UIComponentBase#encodeBegin(javax.faces.context.FacesContext) - */ - public void encodeBegin(FacesContext context) throws IOException - { - if (!isRendered()) - { - return; - } - - ResponseWriter out = context.getResponseWriter(); - - String bgColor = getBgcolor(); - if (bgColor == null) - { - bgColor = PanelGenerator.BGCOLOR_WHITE; - } - - String panel = getBorder(); - if (panel != null) - { - PanelGenerator.generatePanelStart(out, - context.getExternalContext().getRequestContextPath(), - panel, - bgColor); - } - - // Previous Message icon image - clicking shows previous message - out.write("
"); - String field = getHiddenFieldName(); - String leftValue = getClientId(context) + NamingContainer.SEPARATOR_CHAR + Integer.toString(ACTION_PREVIOUS); - String leftOnclick = Utils.generateFormSubmit(context, this, field, leftValue); - out.write(Utils.buildImageTag(context, WebResources.IMAGE_MOVELEFT, 12, 12, null, leftOnclick, "middle")); - out.write(""); - - // get messages for the component and crop the stack to the maximum history size - Iterator msgIterator = context.getMessages(STATUS_MESSAGE); - while (msgIterator.hasNext()) - { - if (messages.size() >= HISTORY_SIZE) - { - messages.remove(HISTORY_SIZE); - } - // add new messages to the stack in turn - messages.add(0, msgIterator.next()); - // reset current message to top if new one added - currentMessage = 0; - } - - // TODO: show different icon depending on SEVERITY of the message? - // Message text - String style = CSS_ERROR; - String icon = WebResources.IMAGE_INFO; - FacesMessage msg = messages.get(currentMessage); - if (msg.getSeverity() == FacesMessage.SEVERITY_INFO) - { - style = CSS_INFO; - } - else if (msg.getSeverity() == FacesMessage.SEVERITY_WARN) - { - style = CSS_WARNING; - } - - out.write(Utils.buildImageTag(context, icon, null, "middle")); - out.write(" "); - out.write(Utils.encode(msg.getSummary())); - out.write(" - "); - out.write(Utils.encode(msg.getDetail())); - out.write(""); - out.write(""); - - // Next Message icon image - clicking shows next message - String rightValue = getClientId(context) + NamingContainer.SEPARATOR_CHAR + Integer.toString(ACTION_NEXT); - String rightOnclick = Utils.generateFormSubmit(context, this, field, rightValue); - out.write(Utils.buildImageTag(context, WebResources.IMAGE_MOVERIGHT, 12, 12, null, rightOnclick, "middle")); - out.write("
"); - - if (panel != null) - { - PanelGenerator.generatePanelEnd(out, - context.getExternalContext().getRequestContextPath(), - panel); - } - } - - /** - * @see javax.faces.component.UIComponentBase#decode(javax.faces.context.FacesContext) - */ - public void decode(FacesContext context) - { - Map requestMap = context.getExternalContext().getRequestParameterMap(); - String fieldId = getHiddenFieldName(); - String value = (String)requestMap.get(fieldId); - - // we encoded the value to start with our Id - if (value != null && value.startsWith(getClientId(context))) - { - // we were clicked, strip out the value - int action = Integer.parseInt(value.substring(getClientId(context).length() + 1)); - - // raise an event to represent the requested action - MessageEvent event = new MessageEvent(this, action); - queueEvent(event); - } - } - - /** - * @see javax.faces.component.UICommand#broadcast(javax.faces.event.FacesEvent) - */ - public void broadcast(FacesEvent event) throws AbortProcessingException - { - if (event instanceof MessageEvent) - { - switch (((MessageEvent)event).Action) - { - case ACTION_NEXT: - currentMessage++; - if (currentMessage >= this.messages.size()) - { - currentMessage = 0; - } - break; - - case ACTION_PREVIOUS: - currentMessage--; - if (currentMessage < 0) - { - currentMessage = this.messages.size() - 1; - } - break; - } - } - else - { - super.broadcast(event); - } - } - - /** - * @return Returns the bgcolor. - */ - public String getBgcolor() - { - ValueBinding vb = getValueBinding("bgcolor"); - if (vb != null) - { - this.bgcolor = (String)vb.getValue(getFacesContext()); - } - - return this.bgcolor; - } - - /** - * @param bgcolor The bgcolor to set. - */ - public void setBgcolor(String bgcolor) - { - this.bgcolor = bgcolor; - } - - /** - * @return Returns the border name. - */ - public String getBorder() - { - ValueBinding vb = getValueBinding("border"); - if (vb != null) - { - this.border = (String)vb.getValue(getFacesContext()); - } - - return this.border; - } - - /** - * @param border The border name to user. - */ - public void setBorder(String border) - { - this.border = border; - } - - - // ------------------------------------------------------------------------------ - // Private helpers - - /** - * We use a hidden field name based on the parent form component Id and - * the string "status" to give a hidden field name that can be shared by all status messages - * within a single UIForm component. - * - * @return hidden field name - */ - private String getHiddenFieldName() - { - UIForm form = Utils.getParentForm(getFacesContext(), this); - return form.getClientId(getFacesContext()) + NamingContainer.SEPARATOR_CHAR + "status"; - } - - - // ------------------------------------------------------------------------------ - // Private members - - public static final String STATUS_MESSAGE = "status-message"; - - private final static String CSS_INFO = "statusInfoText"; - private final static String CSS_WARNING = "statusWarningText"; - private final static String CSS_ERROR = "statusErrorText"; - - private final static int ACTION_PREVIOUS = 0; - private final static int ACTION_NEXT = 1; - - private final static int HISTORY_SIZE = 10; - - private final static String MSG_DEFAULT_STATUS = "status_message_default"; - - private List messages = new LinkedList(); - private int currentMessage = 0; - - // component settings - private String border = null; - private String bgcolor = null; - - - // ------------------------------------------------------------------------------ - // Inner classes - - /** - * Class representing the an action that occurs when the previous/next buttons are clicked. - */ - public static class MessageEvent extends ActionEvent - { - public MessageEvent(UIComponent component, int action) - { - super(component); - Action = action; - } - - public int Action; - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/UploadInput.java b/war/src/main/java/org/alfresco/web/ui/common/component/UploadInput.java deleted file mode 100644 index daeaba62d3..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/UploadInput.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component; - -import java.io.IOException; - -import javax.faces.component.NamingContainer; -import javax.faces.component.html.HtmlInputText; -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; - -import org.alfresco.web.app.Application; -import org.alfresco.web.app.portlet.AlfrescoFacesPortlet; - -public class UploadInput extends HtmlInputText implements NamingContainer -{ - private static final long serialVersionUID = 4064734856565167835L; - - private String framework; - - public void encodeBegin(FacesContext context) throws IOException - { - ResponseWriter writer = context.getResponseWriter(); - String contextPath = context.getExternalContext().getRequestContextPath(); - String path = Application.inPortalServer() ? AlfrescoFacesPortlet.getResourceURL(context, "/uploadFileServlet") - : contextPath + "/uploadFileServlet"; - - writer.write("\n"); - - writer.write("\n"); - - super.encodeBegin(context); - - writer.write("\n"); - } - - public Object saveState(FacesContext context) - { - Object[] values = new Object[2]; - values[0] = super.saveState(context); - values[1] = framework; - return values; - } - - public void restoreState(FacesContext context, Object state) - { - Object[] values = (Object[]) state; - super.restoreState(context, values[0]); - framework = (String) values[1]; - } - - public String getFramework() - { - return framework; - } - - public void setFramework(String framework) - { - this.framework = framework; - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/data/GridArrayDataModel.java b/war/src/main/java/org/alfresco/web/ui/common/component/data/GridArrayDataModel.java deleted file mode 100644 index ba5c9509ce..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/data/GridArrayDataModel.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.data; - -/** - * @author kevinr - */ -public class GridArrayDataModel implements IGridDataModel -{ - /** - * Constructor - * - * @param data Array of Object (beans) row data - */ - public GridArrayDataModel(Object[] data) - { - this.data = data; - } - - /** - * Get a row object for the specified row index - * - * @param index valid row index - * - * @return row object for the specified index - */ - public Object getRow(int index) - { - return this.data[index]; - } - - /** - * Return the number of rows in the data model - * - * @return row count - */ - public int size() - { - return this.data.length; - } - - /** - * Sort the data set using the specified sort parameters - * - * @param column Column to sort - * @param descending True for descending sort, false for ascending - * @param mode Sort mode to use (see IDataContainer constants) - */ - public void sort(String column, boolean descending, String mode) - { - } - - private Object[] data = null; -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/data/GridListDataModel.java b/war/src/main/java/org/alfresco/web/ui/common/component/data/GridListDataModel.java deleted file mode 100644 index b4f3c73c44..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/data/GridListDataModel.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.data; - -import java.util.List; - -import org.alfresco.web.data.QuickSort; - -/** - * @author kevinr - */ -public class GridListDataModel implements IGridDataModel -{ - /** - * Constructor - * - * @param data List of Object[] row data - */ - public GridListDataModel(List data) - { - this.data = data; - } - - /** - * Get a row object for the specified row index - * - * @param index valid row index - * - * @return row object for the specified index - */ - public Object getRow(int index) - { - return this.data.get(index); - } - - /** - * Return the number of rows in the data model - * - * @return row count - */ - public int size() - { - return this.data.size(); - } - - /** - * Sort the data set using the specified sort parameters - * - * @param column Column to sort - * @param descending True for descending sort, false for ascending - * @param mode Sort mode to use (see IDataContainer constants) - */ - public void sort(String column, boolean descending, String mode) - { - try - { - QuickSort sorter = new QuickSort(this.data, column, !descending, mode); - sorter.sort(); - } - catch (Exception err) - { - throw new RuntimeException("Failed to sort data: " + err.getMessage(), err); - } - } - - private List data = null; -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/data/IGridDataModel.java b/war/src/main/java/org/alfresco/web/ui/common/component/data/IGridDataModel.java deleted file mode 100644 index 594f583b6a..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/data/IGridDataModel.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.data; - -import java.io.Serializable; - -/** - * @author kevinr - */ -public interface IGridDataModel extends Serializable -{ - /** - * Get a row object for the specified row index - * - * @param index valid row index - * - * @return row object for the specified index - */ - public Object getRow(int index); - - /** - * Return the number of rows in the data model - * - * @return row count - */ - public int size(); - - /** - * Sort the data set using the specified sort parameters - * - * @param column Column to sort - * @param descending True for descending sort, false for ascending - * @param mode Sort mode to use (see IDataContainer constants) - */ - public void sort(String column, boolean descending, String mode); -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/data/UIColumn.java b/war/src/main/java/org/alfresco/web/ui/common/component/data/UIColumn.java deleted file mode 100644 index bd6da0f2f9..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/data/UIColumn.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.data; - -import javax.faces.component.UIComponent; -import javax.faces.component.UIComponentBase; -import javax.faces.context.FacesContext; -import javax.faces.el.ValueBinding; - -/** - * @author Kevin Roast - */ -public class UIColumn extends UIComponentBase -{ - // ------------------------------------------------------------------------------ - // Component implementation - - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.Data"; - } - - /** - * Return the UI Component to be used as the header for this column - * - * @return UIComponent - */ - public UIComponent getHeader() - { - return getFacet("header"); - } - - /** - * Return the UI Component to be used as the footer for this column - * - * @return UIComponent - */ - public UIComponent getFooter() - { - return getFacet("footer"); - } - - /** - * Return the UI Component to be used as the large icon for this column - * - * @return UIComponent - */ - public UIComponent getLargeIcon() - { - return getFacet("large-icon"); - } - - /** - * Return the UI Component to be used as the small icon for this column - * - * @return UIComponent - */ - public UIComponent getSmallIcon() - { - return getFacet("small-icon"); - } - - /** - * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object) - */ - public void restoreState(FacesContext context, Object state) - { - Object values[] = (Object[])state; - // standard component attributes are restored by the super class - super.restoreState(context, values[0]); - this.primary = ((Boolean)values[1]).booleanValue(); - this.actions = ((Boolean)values[2]).booleanValue(); - } - - /** - * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext) - */ - public Object saveState(FacesContext context) - { - Object values[] = new Object[3]; - // standard component attributes are saved by the super class - values[0] = super.saveState(context); - values[1] = (this.primary ? Boolean.TRUE : Boolean.FALSE); - values[2] = (this.actions ? Boolean.TRUE : Boolean.FALSE); - return (values); - } - - - // ------------------------------------------------------------------------------ - // Strongly typed component property accessors - - /** - * @return true if this is the primary column - */ - public boolean getPrimary() - { - ValueBinding vb = getValueBinding("primary"); - if (vb != null) - { - this.primary = (Boolean)vb.getValue(getFacesContext()); - } - return this.primary; - } - - /** - * @param primary True if this is the primary column, false otherwise - */ - public void setPrimary(boolean primary) - { - this.primary = primary; - } - - /** - * @return true if this is the column containing actions for the current row - */ - public boolean getActions() - { - ValueBinding vb = getValueBinding("actions"); - if (vb != null) - { - this.actions = (Boolean)vb.getValue(getFacesContext()); - } - return this.actions; - } - - /** - * @param actions True if this is the column containing actions for the current row - */ - public void setActions(boolean actions) - { - this.actions = actions; - } - - - // ------------------------------------------------------------------------------ - // Private data - - private boolean primary = false; - private boolean actions = false; -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/data/UIDataPager.java b/war/src/main/java/org/alfresco/web/ui/common/component/data/UIDataPager.java deleted file mode 100644 index cd5fc8abfa..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/data/UIDataPager.java +++ /dev/null @@ -1,658 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.data; - -import java.io.IOException; -import java.text.MessageFormat; -import java.util.Map; -import java.util.ResourceBundle; - -import javax.faces.component.NamingContainer; -import javax.faces.component.UICommand; -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; -import javax.faces.event.AbortProcessingException; -import javax.faces.event.ActionEvent; -import javax.faces.event.FacesEvent; - -import org.alfresco.web.app.Application; -import org.alfresco.web.data.IDataContainer; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.WebResources; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * @author Kevin Roast - */ -public class UIDataPager extends UICommand -{ - private static Log s_logger = LogFactory.getLog(IDataContainer.class); - - private static final String LAST_PAGE = "last_page"; - private static final String NEXT_PAGE = "next_page"; - private static final String PREVIOUS_PAGE = "prev_page"; - private static final String FIRST_PAGE = "first_page"; - private static final String MSG_PAGEINFO = "page_info"; - - private static final int VISIBLE_PAGE_RANGE = 3; - private static final int AMOUNT_FIRST_PAGES = 7; - - // ------------------------------------------------------------------------------ - // Construction - - /** - * Default constructor - */ - public UIDataPager() - { - setRendererType(null); - } - - - // ------------------------------------------------------------------------------ - // Component implementation - - /** - * @see javax.faces.component.UIComponent#encodeBegin(javax.faces.context.FacesContext) - */ - public void encodeBegin(FacesContext context) throws IOException - { - IDataContainer dataContainer = getDataContainer(); - if (dataContainer == null) - { - throw new IllegalStateException("Must nest UISortLink inside component implementing IDataContainer!"); - } - - // this component will only render itself if the parent DataContainer is setup - // with a valid "pageSize" property - if (isRendered() == false || dataContainer.getPageSize() == -1) - { - return; - } - - final String formClientId = Utils.getParentForm(context, this).getClientId(context); - final String pageInputId = getPageInputId(); - final String hiddenFieldName = getHiddenFieldName(); - - ResponseWriter out = context.getResponseWriter(); - ResourceBundle bundle = Application.getBundle(context); - StringBuilder buf = new StringBuilder(512); - - int currentPage = dataContainer.getCurrentPage(); - int pageCount = dataContainer.getPageCount(); - - Object displayInput = getAttributes().get("displayInput"); - - String beginTag = ""); - } - else - { - inputPageNumber.append(""); - } - } - - buf.append(beginTag); - if (getAttributes().get("style") != null) - { - buf.append(" style=\"") - .append(getAttributes().get("style")) - .append(divStyle) - .append('"'); - } - if (getAttributes().get("styleClass") != null) - { - buf.append(" class=") - .append(getAttributes().get("styleClass")); - } - buf.append('>'); - - // output Page X of Y text - buf.append(MessageFormat.format(bundle.getString(MSG_PAGEINFO), new Object[] { - inputPageNumber.toString(), // current page can be zero if no data present - Integer.toString(pageCount) - })); - - buf.append("  "); - - // output HTML links or labels to render the paging controls - // first page - if (currentPage != 0) - { - buf.append(""); - buf.append(Utils.buildImageTag(context, WebResources.IMAGE_FIRSTPAGE, 16, 16, bundle.getString(FIRST_PAGE), null, imageVericalAlign, imageStyle)); - buf.append(""); - } - else - { - buf.append(Utils.buildImageTag(context, WebResources.IMAGE_FIRSTPAGE_NONE, 16, 16, null, null, imageVericalAlign, imageStyle)); - } - - buf.append(" "); - - // previous page - if (currentPage != 0) - { - buf.append(""); - buf.append(Utils.buildImageTag(context, WebResources.IMAGE_PREVIOUSPAGE, 16, 16, bundle.getString(PREVIOUS_PAGE), null, imageVericalAlign, imageStyle)); - buf.append(""); - } - else - { - buf.append(Utils.buildImageTag(context, WebResources.IMAGE_PREVIOUSPAGE_NONE, 16, 16, null, null, imageVericalAlign, imageStyle)); - } - - buf.append(" "); - - Object objType = getAttributes().get("dataPagerType"); - - PagerType type = PagerType.TRACKPAGE; - if (objType instanceof String) - { - try - { - type = PagerType.valueOf((String)objType); - } - catch (Throwable ex) - { - s_logger.warn("DataPager id:" + this.getId() + " with incorrect 'numberPageType' attribute"); - } - } - - switch (type) - { - case STANDARD: - encodeType0(buf, currentPage, pageCount); - break; - case DECADES: - encodeType1(buf, currentPage, pageCount); - break; - case TRACKPAGE: - encodeType2(buf, currentPage, pageCount); - break; - default: - encodeType2(buf, currentPage, pageCount); - } - - // next page - if ((dataContainer.getCurrentPage() < dataContainer.getPageCount() - 1) == true) - { - buf.append(""); - buf.append(Utils.buildImageTag(context, WebResources.IMAGE_NEXTPAGE, 16, 16, bundle.getString(NEXT_PAGE), null, imageVericalAlign, imageStyle)); - buf.append(""); - } - else - { - buf.append(Utils.buildImageTag(context, WebResources.IMAGE_NEXTPAGE_NONE, 16, 16, null, null, imageVericalAlign, imageStyle)); - } - - buf.append(" "); - - // last page - if ((dataContainer.getCurrentPage() < dataContainer.getPageCount() - 1) == true) - { - buf.append(""); - buf.append(Utils.buildImageTag(context, WebResources.IMAGE_LASTPAGE, 16, 16, bundle.getString(LAST_PAGE), null, imageVericalAlign, imageStyle)); - buf.append(""); - } - else - { - buf.append(Utils.buildImageTag(context, WebResources.IMAGE_LASTPAGE_NONE, 16, 16, null, null, imageVericalAlign, imageStyle)); - } - - buf.append(endTag); - - out.write(buf.toString()); - } - - private void createClicableDigitForPage(int num, StringBuilder buf) - { - buf.append("") - .append(num + 1) - .append(" "); - } - - private void createDigitForPage(int num, StringBuilder buf) - { - buf.append("") - .append(num + 1) - .append(" "); - } - - private void encodeType0(StringBuilder buf, int currentPage, int pageCount) - { - int totalIndex = (pageCount < 10 ? pageCount : 10); - for (int i=0; i= 20) - { - buf.append("... "); - totalIndex = (pageCount / 10) * 10; - totalIndex = (totalIndex < 100 ? totalIndex : 100); - for (int i=19; i 10 and not already shown - if ((pageCount > 10) && (pageCount % 10 != 0)) - { - if (pageCount-1 != currentPage) - { - if (pageCount < 20) - { - buf.append("... "); - } - - createClicableDigitForPage(pageCount - 1, buf); - } - else - { - if (pageCount < 20) - { - buf.append("... "); - } - createDigitForPage(pageCount - 1, buf); - } - } - } - - private void encodeType1(StringBuilder buf, int currentPage, int pageCount) - { - // clickable digits for pages 1 to 10 - int totalIndex = (pageCount < 10 ? pageCount : 10); - int number = -1; - if (currentPage == 0) - { - number = generateClickableDigitForPageCurrent(currentPage, pageCount, buf, false, currentPage + VISIBLE_PAGE_RANGE + 1 < pageCount); - } - - if (currentPage > VISIBLE_PAGE_RANGE + 1) - { - createClicableDigitForPage(0, buf); - } - - if (currentPage <= 9 && currentPage != 0) - { - number = generateClickableDigitForPageCurrent(currentPage, pageCount, buf, currentPage > VISIBLE_PAGE_RANGE + 1, currentPage + VISIBLE_PAGE_RANGE + 1 < pageCount); - } - - // clickable digits for pages 20 to 100, 101 to 200, ... (in jumps of 10) - if (number <= 9 && currentPage < 100 && pageCount > 9) - { - createClicableDigitForPage(9, buf); - } - - // clickable digits for pages 20 to 100 (in jumps of 10) - if (pageCount >= 10) - { - int i = 19; - totalIndex = (pageCount / 10) * 10; - totalIndex = (totalIndex < 100 ? totalIndex : 100); - int stepIndex = (currentPage + 1) / 100; - if (stepIndex > 0) - { - i = (100 * stepIndex); - totalIndex = i + 100; - i--; - if (pageCount < totalIndex) - { - totalIndex = pageCount; - } - } - for (; i < totalIndex; i += 10) - { - if (i <= currentPage && currentPage <= (i + VISIBLE_PAGE_RANGE)) - { - generateClickableDigitForPageCurrent(currentPage, pageCount, buf, true, (currentPage + 1 + VISIBLE_PAGE_RANGE) < totalIndex); - continue; - } - if (currentPage < i && currentPage > (i-10 + VISIBLE_PAGE_RANGE)) - { - number = generateClickableDigitForPageCurrent(currentPage, pageCount, buf, true, (currentPage + VISIBLE_PAGE_RANGE + 2) < totalIndex); - if (number + 1 < pageCount) - { - buf.append("... "); - } - if (currentPage + VISIBLE_PAGE_RANGE >= i) - { - continue; - } - } - if (i != currentPage) - { - createClicableDigitForPage(i, buf); - } - else - { - createDigitForPage(i, buf); - } - } - } - - // clickable digits for last page - if (number != pageCount && totalIndex < pageCount) - { - if (pageCount > number) - { - createClicableDigitForPage(pageCount - 1, buf); - } - else - { - createDigitForPage(pageCount - 1, buf); - } - } - } - - private void encodeType2(StringBuilder buf, int currentPage, int pageCount) - { - int number = AMOUNT_FIRST_PAGES; - if (currentPage + VISIBLE_PAGE_RANGE < AMOUNT_FIRST_PAGES) - { - int totalIndex = AMOUNT_FIRST_PAGES < pageCount ? AMOUNT_FIRST_PAGES : pageCount; - for (int i = 0; i < totalIndex; i++) - { - if (i != currentPage) - { - createClicableDigitForPage(i, buf); - } - else - { - createDigitForPage(i, buf); - } - } - if (currentPage + VISIBLE_PAGE_RANGE + 1 < pageCount) - { - buf.append("... "); - } - } - else - { - createClicableDigitForPage(0, buf); - number = generateClickableDigitForPageCurrent(currentPage, pageCount, buf, currentPage > VISIBLE_PAGE_RANGE + 1, (currentPage + 1 + VISIBLE_PAGE_RANGE) < pageCount); - } - - if (number < pageCount) - { - if (pageCount > number) - { - createClicableDigitForPage(pageCount - 1, buf); - } - else - { - createDigitForPage(pageCount - 1, buf); - } - } - } - - //clickable digits for pages current page - 3 and current page + 3 - private int generateClickableDigitForPageCurrent(int currentPage, int pageCount, StringBuilder buf, boolean startDivider, boolean finishDivider) - { - int startPage = currentPage - VISIBLE_PAGE_RANGE; - if (startPage < 0) - { - startPage = 0; - } - if (startDivider) - { - buf.append("... "); - } - for (int i = startPage; i < currentPage; i++) - { - createClicableDigitForPage(i, buf); - } - - buf.append("") - .append(currentPage + 1) - .append(" "); - - int i = currentPage + 1; - int finishPage = currentPage + VISIBLE_PAGE_RANGE; - if (finishPage >= pageCount) - { - finishPage = pageCount - 1; - } - for (; i <= finishPage; i++) - { - createClicableDigitForPage(i, buf); - } - if (finishDivider) - { - buf.append("... "); - } - - return i; - } - - /** - * @see javax.faces.component.UIComponentBase#decode(javax.faces.context.FacesContext) - */ - public void decode(FacesContext context) - { - Map requestMap = context.getExternalContext().getRequestParameterMap(); - String fieldId = getHiddenFieldName(); - String value = (String)requestMap.get(fieldId); - if (value != null && value.length() != 0) - { - // we were clicked - queue an event to represent the click - // cannot handle the event here as other components etc. have not had - // a chance to decode() - we queue an event to be processed later - PageEvent actionEvent = new PageEvent(this, Integer.valueOf(value).intValue()); - this.queueEvent(actionEvent); - } - } - - /** - * @see javax.faces.component.UICommand#broadcast(javax.faces.event.FacesEvent) - */ - public void broadcast(FacesEvent event) throws AbortProcessingException - { - if (event instanceof PageEvent == false) - { - // let the super class handle events which we know nothing about - super.broadcast(event); - } - else - { - // found a sort event for us! - if (s_logger.isDebugEnabled()) - s_logger.debug("Handling paging event to index: " + ((PageEvent)event).Page); - getDataContainer().setCurrentPage(((PageEvent)event).Page); - } - } - - - // ------------------------------------------------------------------------------ - // Private helpers - - /** - * Return the parent data container for this component - */ - private IDataContainer getDataContainer() - { - return Utils.getParentDataContainer(getFacesContext(), this); - } - - /** - * Output the JavaScript event script to jump to a specified page - * - * @param page page index to generate script to jump too - */ - private String generateEventScript(int page, String hiddenFieldName) - { - return Utils.generateFormSubmit(getFacesContext(), this, hiddenFieldName, Integer.toString(page)); - } - - /** - * We use a hidden field name based on the parent data container component Id and - * the string "pager" to give a field name that can be shared by all pager links - * within a single data container component. - * - * @return hidden field name - */ - private String getHiddenFieldName() - { - UIComponent dataContainer = (UIComponent)Utils.getParentDataContainer(getFacesContext(), this); - return dataContainer.getClientId(getFacesContext()) + NamingContainer.SEPARATOR_CHAR + "pager"; - } - - /** - * Output the JavaScript event script to handle onkeypress event in the Page Number input. - * It validates and sends appropriate page number on 'Enter'. - * - * @return JavaScript code - */ - private String generateInputOnkeyPressScript(String pageInputId, String formClientId, String hiddenFieldName) - { - final StringBuilder script = new StringBuilder(128); - script.append("return validateAndSubmit(event,'") - .append(getPageInputId()) - .append("','") - .append(formClientId) - .append("','") - .append(hiddenFieldName) - .append("');"); - return script.toString(); - } - - /** - * Output the JavaScript event script to handle onkeydown event in the Page Number input. - * It handles only digits and some 'useful' keys. - * @return JavaScript code - */ - private String generateInputOnkeydownScript() - { - return "return onlyDigits(event);"; - } - - /** - * Output the JavaScript event script to handle onkeydown event in the Page Number input (For IE6 browser). - * It handles only digits and some 'useful' keys. - * @return JavaScript code - */ - private String generateIE6InputOnkeydownScript(String pageInputId, String formClientId, String hiddenFieldName) - { - final StringBuilder script = new StringBuilder(128); - script.append("return onlyDigitsIE6(event,'") - .append(getPageInputId()) - .append("','") - .append(formClientId) - .append("','") - .append(hiddenFieldName) - .append("');"); - return script.toString(); - } - - private String getPageInputId() - { - return getHiddenFieldName() + NamingContainer.SEPARATOR_CHAR + "pageNamber"; - } - - - // ------------------------------------------------------------------------------ - // Inner classes - - /** - * Class representing the clicking of a sortable column. - */ - private static class PageEvent extends ActionEvent - { - private static final long serialVersionUID = -5338654505243607790L; - - public PageEvent(UIComponent component, int page) - { - super(component); - Page = page; - } - public int Page = 0; - } - - - /** - * Enumeration of the available Data Pager display types see ETWOONE-389 - */ - private enum PagerType - { - STANDARD, DECADES, TRACKPAGE - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/data/UIRichList.java b/war/src/main/java/org/alfresco/web/ui/common/component/data/UIRichList.java deleted file mode 100644 index 6abf97e205..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/data/UIRichList.java +++ /dev/null @@ -1,589 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.data; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.component.UIComponent; -import javax.faces.component.UIComponentBase; -import javax.faces.context.FacesContext; -import javax.faces.el.ValueBinding; -import javax.transaction.UserTransaction; - -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Repository; -import org.alfresco.web.config.ViewsConfigElement; -import org.alfresco.web.data.IDataContainer; -import org.alfresco.web.ui.common.renderer.data.IRichListRenderer; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * @author Kevin Roast - */ -public class UIRichList extends UIComponentBase implements IDataContainer,Serializable -{ - // ------------------------------------------------------------------------------ - // Construction - - private static final long serialVersionUID = 4302199745018058173L; - - /** - * Default constructor - */ - public UIRichList() - { - setRendererType("org.alfresco.faces.RichListRenderer"); - - // get the list of views from the client configuration - ViewsConfigElement viewsConfig = (ViewsConfigElement)Application.getConfigService( - FacesContext.getCurrentInstance()).getConfig("Views"). - getConfigElement(ViewsConfigElement.CONFIG_ELEMENT_ID); - List views = viewsConfig.getViews(); - - // instantiate each renderer and add to the list - for (String view : views) - { - try - { - Class clazz = Class.forName(view); - IRichListRenderer renderer = (IRichListRenderer)clazz.newInstance(); - viewRenderers.put(renderer.getViewModeID(), renderer); - - if (logger.isDebugEnabled()) - logger.debug("Added view '" + renderer.getViewModeID() + "' to UIRichList"); - } - catch (Exception e) - { - if (logger.isWarnEnabled()) - { - logger.warn("Failed to create renderer: " + view, e); - } - } - } - } - - - // ------------------------------------------------------------------------------ - // Component implementation - - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.Data"; - } - - /** - * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object) - */ - public void restoreState(FacesContext context, Object state) - { - Object values[] = (Object[])state; - // standard component attributes are restored by the super class - super.restoreState(context, values[0]); - this.currentPage = ((Integer)values[1]).intValue(); - this.sortColumn = (String)values[2]; - this.sortDescending = ((Boolean)values[3]).booleanValue(); - this.value = values[4]; // not serializable! - this.dataModel = (IGridDataModel)values[5]; // not serializable! - this.viewMode = (String)values[6]; - this.pageSize = ((Integer)values[7]).intValue(); - this.initialSortColumn = (String)values[8]; - this.initialSortDescending = ((Boolean)values[9]).booleanValue(); - this.refreshOnBind = ((Boolean)values[10]).booleanValue(); - } - - /** - * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext) - */ - public Object saveState(FacesContext context) - { - Object values[] = new Object[] { - // standard component attributes are saved by the super class - super.saveState(context), - Integer.valueOf(this.currentPage), - this.sortColumn, - (this.sortDescending ? Boolean.TRUE : Boolean.FALSE), - this.value, - this.dataModel, - this.viewMode, - Integer.valueOf(this.pageSize), - this.initialSortColumn, - (this.initialSortDescending ? Boolean.TRUE : Boolean.FALSE), - this.refreshOnBind}; - - return (values); - } - - /** - * Get the value (for this component the value is an object used as the DataModel) - * - * @return the value - */ - public Object getValue() - { - if (this.value == null) - { - ValueBinding vb = getValueBinding("value"); - if (vb != null) - { - this.value = vb.getValue(getFacesContext()); - } - } - return this.value; - } - - /** - * Set the value (for this component the value is an object used as the DataModel) - * - * @param value the value - */ - public void setValue(Object value) - { - this.dataModel = null; - this.value = value; - } - - /** - * Clear the current sorting settings back to the defaults - */ - public void clearSort() - { - this.sortColumn = null; - this.sortDescending = true; - this.initialSortColumn = null; - this.initialSortDescending = false; - } - - /** - * Get the view mode for this Rich List - * - * @return view mode as a String - */ - public String getViewMode() - { - ValueBinding vb = getValueBinding("viewMode"); - if (vb != null) - { - this.viewMode = (String)vb.getValue(getFacesContext()); - } - - return this.viewMode; - } - - /** - * Set the current view mode for this Rich List - * - * @param viewMode the view mode as a String - */ - public void setViewMode(String viewMode) - { - this.viewMode = viewMode; - } - - /** - * Get the refreshOnBind flag. - * - * @return the refreshOnBind - */ - public boolean getRefreshOnBind() - { - ValueBinding vb = getValueBinding("refreshOnBind"); - if (vb != null) - { - this.refreshOnBind = (Boolean)vb.getValue(getFacesContext()); - } - return this.refreshOnBind; - } - - /** - * Set the refreshOnBind flag. True to force the list to retrieve bound data on bind(). - * - * @param refreshOnBind the refreshOnBind - */ - public void setRefreshOnBind(boolean refreshOnBind) - { - this.refreshOnBind = refreshOnBind; - } - - /** - * Return the UI Component to be used as the "no items available" message - * - * @return UIComponent - */ - public UIComponent getEmptyMessage() - { - return getFacet("empty"); - } - - - // ------------------------------------------------------------------------------ - // IDataContainer implementation - - /** - * Return the currently sorted column if any - * - * @return current sorted column if any - */ - public String getCurrentSortColumn() - { - return this.sortColumn; - } - - /** - * @see org.alfresco.web.data.IDataContainer#isCurrentSortDescending() - */ - public boolean isCurrentSortDescending() - { - return this.sortDescending; - } - - /** - * @return Returns the initialSortColumn. - */ - public String getInitialSortColumn() - { - return this.initialSortColumn; - } - - /** - * @param initialSortColumn The initialSortColumn to set. - */ - public void setInitialSortColumn(String initialSortColumn) - { - this.initialSortColumn = initialSortColumn; - } - - /** - * @return Returns the initialSortDescending. - */ - public boolean isInitialSortDescending() - { - return this.initialSortDescending; - } - - /** - * @param initialSortDescending The initialSortDescending to set. - */ - public void setInitialSortDescending(boolean initialSortDescending) - { - this.initialSortDescending = initialSortDescending; - } - - /** - * Returns the current page size used for this list, or -1 for no paging. - */ - public int getPageSize() - { - ValueBinding vb = getValueBinding("pageSize"); - if (vb != null) - { - int pageSize = ((Integer)vb.getValue(getFacesContext())).intValue(); - if (pageSize != this.pageSize) - { - // force a reset of the current page - else the bind may show a page that isn't there - setPageSize(pageSize); - } - } - - return this.pageSize; - } - - /** - * Sets the current page size used for the list. - * - * @param val int - */ - public void setPageSize(int val) - { - if (val >= -1) - { - this.pageSize = val; - setCurrentPage(0); - } - } - - /** - * @see org.alfresco.web.data.IDataContainer#getPageCount() - */ - public int getPageCount() - { - return this.pageCount; - } - - /** - * Return the current page the list is displaying - * - * @return current page zero based index - */ - public int getCurrentPage() - { - return this.currentPage; - } - - /** - * @see org.alfresco.web.data.IDataContainer#setCurrentPage(int) - */ - public void setCurrentPage(int index) - { - this.currentPage = index; - this.sortOrPageChanged = true; - } - - /** - * Returns true if a row of data is available - * - * @return true if data is available, false otherwise - */ - public boolean isDataAvailable() - { - return this.rowIndex < this.maxRowIndex; - } - - /** - * Returns the next row of data from the data model - * - * @return next row of data as a Bean object - */ - public Object nextRow() - { - // get next row and increment row count - Object rowData = getDataModel().getRow(this.rowIndex + 1); - - // Prepare the data-binding variable "var" ready for the next cycle of - // renderering for the child components. - String var = (String)getAttributes().get("var"); - if (var != null) - { - Map requestMap = getFacesContext().getExternalContext().getRequestMap(); - if (isDataAvailable() == true) - { - requestMap.put(var, rowData); - } - else - { - requestMap.remove(var); - } - } - - this.rowIndex++; - - return rowData; - } - - /** - * Sort the dataset using the specified sort parameters - * - * @param column Column to sort - * @param descending True for descending sort, false for ascending - * @param mode Sort mode to use (see IDataContainer constants) - */ - public void sort(String column, boolean descending, String mode) - { - this.sortColumn = column; - this.sortDescending = descending; - this.sortOrPageChanged = true; - - // delegate to the data model to sort its contents - // place in a UserTransaction as we may need to perform a LOT of node calls to complete - UserTransaction tx = null; - try - { - if (getDataModel().size() > 16) - { - FacesContext context = FacesContext.getCurrentInstance(); - tx = Repository.getUserTransaction(context, true); - tx.begin(); - } - - getDataModel().sort(column, descending, mode); - - // commit the transaction - if (tx != null) - { - tx.commit(); - } - } - catch (Throwable err) - { - try { if (tx != null) {tx.rollback();} } catch (Exception tex) {} - } - } - - - // ------------------------------------------------------------------------------ - // UIRichList implementation - - /** - * Method called to bind the RichList component state to the data model value - */ - public void bind() - { - if (getRefreshOnBind() == true) - { - this.value = null; - this.dataModel = null; - } - int rowCount = getDataModel().size(); - // if a page size is specified, then we use that - int pageSize = getPageSize(); - if (pageSize != -1 && pageSize != 0) - { - // calc total number of pages available - this.pageCount = (rowCount / this.pageSize) + 1; - - if (rowCount % pageSize == 0 && this.pageCount != 1) - { - this.pageCount--; - } - - // set currentPage as lastPage if input digit in UIDataPager > pageCount - if (this.currentPage >= this.pageCount) - { - this.currentPage = this.pageCount - 1; - } - - // calc start row index based on current page index - this.rowIndex = (this.currentPage * pageSize) - 1; - - // calc the maximum row index that can be returned - this.maxRowIndex = this.rowIndex + pageSize; - if (this.maxRowIndex >= rowCount) - { - this.maxRowIndex = rowCount - 1; - } - } - // else we are not paged so show all data from start - else - { - this.rowIndex = -1; - this.pageCount = 1; - this.maxRowIndex = (rowCount - 1); - } - if (logger.isDebugEnabled()) - logger.debug("Bound datasource: PageSize: " + pageSize + "; CurrentPage: " + this.currentPage + "; RowIndex: " + this.rowIndex + "; MaxRowIndex: " + this.maxRowIndex + "; RowCount: " + rowCount); - } - - /** - * @return A new IRichListRenderer implementation for the current view mode - */ - public IRichListRenderer getViewRenderer() - { - // get type from current view mode, then create an instance of the renderer - IRichListRenderer renderer = null; - if (getViewMode() != null) - { - renderer = (IRichListRenderer)viewRenderers.get(getViewMode()); - } - return renderer; - } - - /** - * Return the data model wrapper - * - * @return IGridDataModel - */ - private IGridDataModel getDataModel() - { - if (this.dataModel == null) - { - // build the appropriate data-model wrapper object - Object val = getValue(); - if (val instanceof List) - { - this.dataModel = new GridListDataModel((List)val); - } - else if ( (java.lang.Object[].class).isAssignableFrom(val.getClass()) ) - { - this.dataModel = new GridArrayDataModel((Object[])val); - } - else - { - throw new IllegalStateException("UIRichList 'value' attribute binding should specify data model of a supported type!"); - } - - // sort first time on initially sorted column if set - if (this.sortColumn == null) - { - String initialSortColumn = getInitialSortColumn(); - if (initialSortColumn != null && initialSortColumn.length() != 0) - { - boolean descending = isInitialSortDescending(); - - // TODO: add support for retrieving correct column sort mode here - this.sortColumn = initialSortColumn; - this.sortDescending = descending; - } - } - if (this.sortColumn != null) - { - // delegate to the data model to sort its contents - this.dataModel.sort(this.sortColumn, this.sortDescending, IDataContainer.SORT_CASEINSENSITIVE); - } - - // reset current page - if (this.sortOrPageChanged == false) - { - this.currentPage = 0; - } - this.sortOrPageChanged = false; - } - - return this.dataModel; - } - - - // ------------------------------------------------------------------------------ - // Private data - - /** map of available IRichListRenderer instances */ - protected final Map viewRenderers = new HashMap(4, 1.0f); - - // component state - private int currentPage = 0; - private String sortColumn = null; - private boolean sortDescending = true; - private Object value = null; - private IGridDataModel dataModel = null; - private String viewMode = null; - private int pageSize = -1; - private String initialSortColumn = null; - private boolean initialSortDescending = false; - private boolean refreshOnBind = false; - - // transient component state that exists during a single page refresh only - private int rowIndex = -1; - private int maxRowIndex = -1; - private int pageCount = 1; - private boolean sortOrPageChanged = false; - - private static Log logger = LogFactory.getLog(IDataContainer.class); -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/data/UISortLink.java b/war/src/main/java/org/alfresco/web/ui/common/component/data/UISortLink.java deleted file mode 100644 index bb38b139c8..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/data/UISortLink.java +++ /dev/null @@ -1,352 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.data; - -import java.io.IOException; -import java.util.Map; - -import javax.faces.component.NamingContainer; -import javax.faces.component.UICommand; -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; -import javax.faces.el.ValueBinding; -import javax.faces.event.AbortProcessingException; -import javax.faces.event.ActionEvent; -import javax.faces.event.FacesEvent; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.alfresco.web.data.IDataContainer; -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.WebResources; - -/** - * @author Kevin Roast - */ -public class UISortLink extends UICommand -{ - /** - * Default Constructor - */ - public UISortLink() - { - setRendererType(null); - } - - /** - * @see javax.faces.component.UIComponent#encodeBegin(javax.faces.context.FacesContext) - */ - public void encodeBegin(FacesContext context) throws IOException - { - ResponseWriter out = context.getResponseWriter(); - - IDataContainer dataContainer = getDataContainer(); - if (dataContainer == null) - { - throw new IllegalStateException("Must nest UISortLink inside component implementing IDataContainer!"); - } - - // swap sort direction if we were last sorted column - boolean bPreviouslySorted = false; - boolean descending = true; - String lastSortedColumn = dataContainer.getCurrentSortColumn(); - if (lastSortedColumn != null && lastSortedColumn.equals(getValue())) - { - descending = !dataContainer.isCurrentSortDescending(); - bPreviouslySorted = true; - } - - // render sort link - StringBuilder buf = new StringBuilder(256); - buf.append(""); - - out.write(buf.toString()); - } - - /** - * @see javax.faces.component.UIComponent#decode(javax.faces.context.FacesContext) - */ - public void decode(FacesContext context) - { - Map requestMap = context.getExternalContext().getRequestParameterMap(); - String fieldId = getHiddenFieldName(context); - String value = (String)requestMap.get(fieldId); - if (value != null && value.equals(getClientId(context))) - { - // we were clicked - queue an event to represent the click - // cannot handle the event here as other components etc. have not had - // a chance to decode() - we queue an event to be processed later - SortEvent actionEvent = new SortEvent(this, (String)this.getValue()); - this.queueEvent(actionEvent); - } - } - - /** - * @see javax.faces.component.UIComponent#broadcast(javax.faces.event.FacesEvent) - */ - public void broadcast(FacesEvent event) throws AbortProcessingException - { - if (event instanceof SortEvent == false) - { - // let the super class handle events which we know nothing about - super.broadcast(event); - } - else if ( ((SortEvent)event).Column.equals(getColumn()) ) - { - // found a sort event for us! - if (s_logger.isDebugEnabled()) - s_logger.debug("Handling sort event for column: " + ((SortEvent)event).Column); - - if (getColumn().equals(getDataContainer().getCurrentSortColumn()) == true) - { - // reverse sort direction - this.descending = !this.descending; - } - else - { - // revert to default sort direction - this.descending = true; - } - getDataContainer().sort(getColumn(), this.descending, getMode()); - } - } - - /** - * We use a hidden field name based on the parent data container component Id and - * the string "sort" to give a field name that can be shared by all sort links - * within a single data container component. - * - * @param context FacesContext - * - * @return hidden field name - */ - private String getHiddenFieldName(FacesContext context) - { - UIComponent dataContainer = (UIComponent)Utils.getParentDataContainer(context, this); - return dataContainer.getClientId(context) + NamingContainer.SEPARATOR_CHAR + "sort"; - } - - /** - * Column name referenced by this link - * - * @return column name - */ - public String getColumn() - { - return (String)getValue(); - } - - /** - * Sorting mode - see IDataContainer constants - * - * @return sorting mode - see IDataContainer constants - */ - public String getMode() - { - return this.mode; - } - - /** - * Set the sorting mode - see IDataContainer constants - * - * @param sortMode the sorting mode- see IDataContainer constants - */ - public void setMode(String sortMode) - { - this.mode = sortMode; - } - - /** - * Returns true for descending sort, false for ascending - * - * @return true for descending sort, false for ascending - */ - public boolean isDescending() - { - return this.descending; - } - - /** - * @return Returns the label. - */ - public String getLabel() - { - ValueBinding vb = getValueBinding("label"); - if (vb != null) - { - this.label = (String)vb.getValue(getFacesContext()); - } - return this.label; - } - - /** - * @param label The label to set. - */ - public void setLabel(String label) - { - this.label = label; - } - - /** - * @return Returns the tooltip. - */ - public String getTooltip() - { - ValueBinding vb = getValueBinding("tooltip"); - if (vb != null) - { - this.tooltip = (String)vb.getValue(getFacesContext()); - } - return this.tooltip; - } - - /** - * @param tooltip The tooltip to set. - */ - public void setTooltip(String tooltip) - { - this.tooltip = tooltip; - } - - /** - * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object) - */ - public void restoreState(FacesContext context, Object state) - { - Object values[] = (Object[])state; - // standard component attributes are restored by the super class - super.restoreState(context, values[0]); - this.descending = ((Boolean)values[1]).booleanValue(); - this.mode = (String)values[2]; - this.label = (String)values[3]; - this.tooltip = (String)values[4]; - } - - /** - * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext) - */ - public Object saveState(FacesContext context) - { - Object values[] = new Object[5]; - // standard component attributes are saved by the super class - values[0] = super.saveState(context); - values[1] = (this.descending ? Boolean.TRUE : Boolean.FALSE); - values[2] = this.mode; - values[3] = this.label; - values[4] = this.tooltip; - return values; - } - - /** - * Return the parent data container for this component - */ - private IDataContainer getDataContainer() - { - return Utils.getParentDataContainer(getFacesContext(), this); - } - - - // ------------------------------------------------------------------------------ - // Inner classes - - /** - * Class representing the clicking of a sortable column. - */ - private static class SortEvent extends ActionEvent - { - public SortEvent(UIComponent component, String column) - { - super(component); - Column = column; - } - - public String Column = null; - } - - - // ------------------------------------------------------------------------------ - // Constants - - private static Log s_logger = LogFactory.getLog(IDataContainer.class); - - /** sorting mode */ - private String mode = IDataContainer.SORT_CASEINSENSITIVE; - - private String label; - - private String tooltip; - - /** true for descending sort, false for ascending */ - private boolean descending = false; -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/debug/BaseDebugComponent.java b/war/src/main/java/org/alfresco/web/ui/common/component/debug/BaseDebugComponent.java deleted file mode 100644 index e211997a8b..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/debug/BaseDebugComponent.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.debug; - -import java.io.IOException; -import java.util.Map; - -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; -import javax.faces.el.ValueBinding; - -import org.alfresco.web.app.Application; -import org.alfresco.web.ui.common.Utils; -import org.springframework.extensions.webscripts.ui.common.component.SelfRenderingComponent; - -/** - * Base class for all debug components - * - * @author gavinc - */ -public abstract class BaseDebugComponent extends SelfRenderingComponent -{ - private String title; - - private static String COMPONENT_PROPERTY = "component_property"; - private static String COMPONENT_VALUE = "component_value"; - - /** - * Retrieves the debug data to show for the component as a Map - * - * @return The Map of data - */ - public abstract Map getDebugData(); - - /** - * @see javax.faces.component.UIComponent#encodeBegin(javax.faces.context.FacesContext) - */ - public void encodeBegin(FacesContext context) throws IOException - { - if (isRendered() == false) - { - return; - } - - ResponseWriter out = context.getResponseWriter(); - out.write(""); - - if (this.getTitle() != null) - { - out.write(""); - } - - out.write(""); - - Map session = getDebugData(); - for (Object key : session.keySet()) - { - out.write(""); - } - - out.write("
"); - out.write(this.getTitle()); - out.write("
"); - out.write(Application.getMessage(context, COMPONENT_PROPERTY)); - out.write(""); - out.write(Application.getMessage(context, COMPONENT_VALUE)); - out.write("
"); - out.write(Utils.encode(key.toString())); - out.write(""); - Object obj = session.get(key); - if (obj == null) - { - out.write("null"); - } - else - { - String value = obj.toString(); - if (value.length() == 0) - { - out.write(" "); - } - else - { - // replace any ; characters with ; as that will help break up long lines - value = value.replaceAll(";", "; "); - out.write(Utils.encode(value)); - } - } - out.write("
"); - - super.encodeBegin(context); - } - - /** - * @see javax.faces.component.UIComponent#getRendersChildren() - */ - public boolean getRendersChildren() - { - return false; - } - - /** - * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object) - */ - public void restoreState(FacesContext context, Object state) - { - Object values[] = (Object[])state; - // standard component attributes are restored by the super class - super.restoreState(context, values[0]); - this.title = (String)values[1]; - } - - /** - * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext) - */ - public Object saveState(FacesContext context) - { - Object values[] = new Object[2]; - // standard component attributes are saved by the super class - values[0] = super.saveState(context); - values[1] = this.title; - return (values); - } - - /** - * Returns the title - * - * @return The title - */ - public String getTitle() - { - ValueBinding vb = getValueBinding("title"); - if (vb != null) - { - this.title = (String)vb.getValue(getFacesContext()); - } - - return this.title; - } - - /** - * Sets the title - * - * @param title The title - */ - public void setTitle(String title) - { - this.title = title; - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/debug/UIHttpApplicationState.java b/war/src/main/java/org/alfresco/web/ui/common/component/debug/UIHttpApplicationState.java deleted file mode 100644 index 574836c63c..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/debug/UIHttpApplicationState.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.debug; - -import java.util.Map; - -import javax.faces.context.FacesContext; - -/** - * Component which displays the current state of the HTTP session - * - * @author gavinc - */ -public class UIHttpApplicationState extends BaseDebugComponent -{ - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.debug.HttpApplicationState"; - } - - /** - * @see org.alfresco.web.ui.common.component.debug.BaseDebugComponent#getDebugData() - */ - public Map getDebugData() - { - return FacesContext.getCurrentInstance().getExternalContext().getApplicationMap(); - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/debug/UIHttpRequestHeaders.java b/war/src/main/java/org/alfresco/web/ui/common/component/debug/UIHttpRequestHeaders.java deleted file mode 100644 index 489004f57c..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/debug/UIHttpRequestHeaders.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.debug; - -import java.util.Map; - -import javax.faces.context.FacesContext; - -/** - * Component which displays the headers for the current HTTP request - * - * @author gavinc - */ -public class UIHttpRequestHeaders extends BaseDebugComponent -{ - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.debug.HttpRequestHeaders"; - } - - /** - * @see org.alfresco.web.ui.common.component.debug.BaseDebugComponent#getDebugData() - */ - public Map getDebugData() - { - return FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap(); - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/debug/UIHttpRequestParams.java b/war/src/main/java/org/alfresco/web/ui/common/component/debug/UIHttpRequestParams.java deleted file mode 100644 index fda9984f15..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/debug/UIHttpRequestParams.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.debug; - -import java.util.Map; - -import javax.faces.context.FacesContext; - -/** - * Component which displays the parameters for the current HTTP request - * - * @author gavinc - */ -public class UIHttpRequestParams extends BaseDebugComponent -{ - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.debug.HttpRequestParams"; - } - - /** - * @see org.alfresco.web.ui.common.component.debug.BaseDebugComponent#getDebugData() - */ - public Map getDebugData() - { - return FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap(); - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/debug/UIHttpRequestState.java b/war/src/main/java/org/alfresco/web/ui/common/component/debug/UIHttpRequestState.java deleted file mode 100644 index 13d36b4c23..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/debug/UIHttpRequestState.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.debug; - -import java.util.Map; - -import javax.faces.context.FacesContext; - -/** - * Component which displays the current state of the HTTP request - * - * @author gavinc - */ -public class UIHttpRequestState extends BaseDebugComponent -{ - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.debug.HttpRequestState"; - } - - /** - * @see org.alfresco.web.ui.common.component.debug.BaseDebugComponent#getDebugData() - */ - public Map getDebugData() - { - return FacesContext.getCurrentInstance().getExternalContext().getRequestMap(); - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/debug/UIHttpSessionState.java b/war/src/main/java/org/alfresco/web/ui/common/component/debug/UIHttpSessionState.java deleted file mode 100644 index 6b02c565c8..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/debug/UIHttpSessionState.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.debug; - -import java.util.Map; - -import javax.faces.context.FacesContext; - -/** - * Component which displays the current state of the HTTP session - * - * @author gavinc - */ -public class UIHttpSessionState extends BaseDebugComponent -{ - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.debug.HttpSessionState"; - } - - /** - * @see org.alfresco.web.ui.common.component.debug.BaseDebugComponent#getDebugData() - */ - public Map getDebugData() - { - return FacesContext.getCurrentInstance().getExternalContext().getSessionMap(); - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/debug/UIRepositoryProperties.java b/war/src/main/java/org/alfresco/web/ui/common/component/debug/UIRepositoryProperties.java deleted file mode 100644 index 29d6d5c017..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/debug/UIRepositoryProperties.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.debug; - -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -import javax.faces.context.FacesContext; - -import org.alfresco.repo.admin.patch.AppliedPatch; -import org.alfresco.repo.admin.patch.PatchService; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.descriptor.Descriptor; -import org.alfresco.service.descriptor.DescriptorService; -import org.alfresco.web.app.Application; -import org.alfresco.web.bean.repository.Repository; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.jsf.FacesContextUtils; - -/** - * Component which displays the Alfresco Repository properties - * - * @author kevinr - */ -public class UIRepositoryProperties extends BaseDebugComponent -{ - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.debug.RepositoryProperties"; - } - - /** - * @see org.alfresco.web.ui.common.component.debug.BaseDebugComponent#getDebugData() - */ - @SuppressWarnings("unchecked") - public Map getDebugData() - { - // note: sort properties - Map properties = new TreeMap(); - - FacesContext fc = FacesContext.getCurrentInstance(); - ServiceRegistry services = Repository.getServiceRegistry(fc); - DescriptorService descriptorService = services.getDescriptorService(); - - Descriptor installedRepoDescriptor = descriptorService.getInstalledRepositoryDescriptor(); - properties.put("Installed Version", installedRepoDescriptor.getVersion()); - properties.put("Installed Schema", installedRepoDescriptor.getSchema()); - - Descriptor systemDescriptor = descriptorService.getServerDescriptor(); - properties.put("Server Version", systemDescriptor.getVersion()); - properties.put("Server Schema", systemDescriptor.getSchema()); - - WebApplicationContext cx = FacesContextUtils.getRequiredWebApplicationContext(fc); - PatchService patchService = (PatchService)cx.getBean("PatchService"); - List patches = patchService.getPatches(null, null); - for (AppliedPatch patch : patches) - { - StringBuilder data = new StringBuilder(256); - data.append(patch.getAppliedOnDate()) - .append(" - ") - .append(patch.getDescription()) - .append(" - ") - .append(patch.getSucceeded() == true ? - Application.getMessage(fc, "repository_patch_succeeded") : - Application.getMessage(fc, "repository_patch_failed")); - properties.put(patch.getId(), data); - } - - return properties; - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/debug/UISystemProperties.java b/war/src/main/java/org/alfresco/web/ui/common/component/debug/UISystemProperties.java deleted file mode 100644 index 33681e00a4..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/debug/UISystemProperties.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.debug; - -import java.util.Map; -import java.util.TreeMap; - -/** - * Component which displays the system properties of the VM - * - * @author gavinc - */ -public class UISystemProperties extends BaseDebugComponent -{ - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.debug.SystemProperties"; - } - - /** - * @see org.alfresco.web.ui.common.component.debug.BaseDebugComponent#getDebugData() - */ - @SuppressWarnings("unchecked") - public Map getDebugData() - { - // note: sort properties - Map properties = new TreeMap(); - - // add the jvm system properties - Map systemProperties = System.getProperties(); - properties.putAll(systemProperties); - - // add heap size properties - properties.put("heap.size", formatBytes(Runtime.getRuntime().totalMemory())); - properties.put("heap.maxsize", formatBytes(Runtime.getRuntime().maxMemory())); - properties.put("heap.free", formatBytes(Runtime.getRuntime().freeMemory())); - - return properties; - } - - /** - * Helper to format bytes for human output - * - * @param bytes bytes - * @return formatted string - */ - private static String formatBytes(long bytes) - { - float f = bytes / 1024l; - f = f / 1024l; - return String.format("%.3fMB (%d bytes)", f, bytes); - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/description/UIDescription.java b/war/src/main/java/org/alfresco/web/ui/common/component/description/UIDescription.java deleted file mode 100644 index 5cb53308d8..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/description/UIDescription.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.description; - -import java.io.Serializable; - -import javax.faces.context.FacesContext; -import javax.faces.el.ValueBinding; - -import org.springframework.extensions.webscripts.ui.common.component.SelfRenderingComponent; - -/** - * Description component that outputs a dynamic description - * - * @author gavinc - */ -public class UIDescription extends SelfRenderingComponent implements Serializable -{ - private static final long serialVersionUID = -2319791691993957792L; - - private String controlValue; - private String text; - - /** - * @return The control value the description is for - */ - public String getControlValue() - { - if (this.controlValue == null) - { - ValueBinding vb = getValueBinding("controlValue"); - if (vb != null) - { - this.controlValue = (String)vb.getValue(getFacesContext()); - } - } - - return this.controlValue; - } - - /** - * @param controlValue Sets the control value this description is for - */ - public void setControlValue(String controlValue) - { - this.controlValue = controlValue; - } - - /** - * @return Returns the description text - */ - public String getText() - { - if (this.text == null) - { - ValueBinding vb = getValueBinding("text"); - if (vb != null) - { - this.text = (String)vb.getValue(getFacesContext()); - } - } - - return this.text; - } - - /** - * @param text Sets the description text - */ - public void setText(String text) - { - this.text = text; - } - - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.Description"; - } - - /** - * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object) - */ - public void restoreState(FacesContext context, Object state) - { - Object values[] = (Object[])state; - // standard component attributes are restored by the super class - super.restoreState(context, values[0]); - this.controlValue = (String)values[1]; - this.text = (String)values[2]; - } - - /** - * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext) - */ - public Object saveState(FacesContext context) - { - Object values[] = new Object[3]; - // standard component attributes are saved by the super class - values[0] = super.saveState(context); - values[1] = this.controlValue; - values[2] = this.text; - return (values); - } - - /** - * @see javax.faces.component.UIComponent#getRendersChildren() - */ - public boolean getRendersChildren() - { - return false; - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/description/UIDescriptions.java b/war/src/main/java/org/alfresco/web/ui/common/component/description/UIDescriptions.java deleted file mode 100644 index 614c9a8964..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/description/UIDescriptions.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.description; - -import javax.faces.context.FacesContext; -import javax.faces.el.ValueBinding; - -import org.springframework.extensions.webscripts.ui.common.component.SelfRenderingComponent; - -/** - * Descriptions component that outputs descriptions held in a backing object - * - * @author gavinc - */ -public class UIDescriptions extends SelfRenderingComponent -{ - private Object value; - - /** - * @return Returns the object holding the decriptions - */ - public Object getValue() - { - if (this.value == null) - { - ValueBinding vb = getValueBinding("value"); - if (vb != null) - { - this.value = vb.getValue(getFacesContext()); - } - } - - return this.value; - } - - /** - * @param value Sets the object holding the description - */ - public void setValue(Object value) - { - this.value = value; - } - - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.Descriptions"; - } - - /** - * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object) - */ - public void restoreState(FacesContext context, Object state) - { - Object values[] = (Object[])state; - // standard component attributes are restored by the super class - super.restoreState(context, values[0]); - this.value = values[1]; - } - - /** - * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext) - */ - public Object saveState(FacesContext context) - { - Object values[] = new Object[2]; - // standard component attributes are saved by the super class - values[0] = super.saveState(context); - values[1] = this.value; - return (values); - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/description/UIDynamicDescription.java b/war/src/main/java/org/alfresco/web/ui/common/component/description/UIDynamicDescription.java deleted file mode 100644 index 03d8bf1722..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/description/UIDynamicDescription.java +++ /dev/null @@ -1,276 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.description; - -import java.io.IOException; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; -import javax.faces.el.ValueBinding; - -import org.alfresco.web.ui.common.Utils; -import org.springframework.extensions.webscripts.ui.common.component.SelfRenderingComponent; - -/** - * Dynamic description component that switches text based on the events - * of another input control - * - * @author gavinc - */ -public class UIDynamicDescription extends SelfRenderingComponent -{ - private String selected; - private String functionName; - - /** - * @return The id of the selected description - */ - public String getSelected() - { - if (this.selected == null) - { - ValueBinding vb = getValueBinding("selected"); - if (vb != null) - { - this.selected = (String)vb.getValue(getFacesContext()); - } - } - - return this.selected; - } - - /** - * @param selected The id of the selected - */ - public void setSelected(String selected) - { - this.selected = selected; - } - - /** - * @return Returns the JavaScript function name to use - */ - public String getFunctionName() - { - if (this.functionName == null) - { - this.functionName = "itemSelected"; - } - - return this.functionName; - } - - /** - * @param functionName Sets the name of the JavaScript function to use - */ - public void setFunctionName(String functionName) - { - this.functionName = functionName; - } - - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public String getFamily() - { - return "org.alfresco.faces.DynamicDescription"; - } - - /** - * @see javax.faces.component.UIComponent#encodeBegin(javax.faces.context.FacesContext) - */ - public void encodeBegin(FacesContext context) throws IOException - { - if (this.isRendered() == false) - { - return; - } - - // output the required JavaScript - ResponseWriter out = context.getResponseWriter(); - - out.write("\n"); - } - - /** - * @see javax.faces.component.UIComponent#encodeChildren(javax.faces.context.FacesContext) - */ - @SuppressWarnings("unchecked") - public void encodeChildren(FacesContext context) throws IOException - { - if (this.isRendered() == false) - { - return; - } - - List kids = getChildren(); - for (UIComponent child : kids) - { - if (child instanceof UIDescription) - { - // render the single description - renderDescription(context, ((UIDescription)child).getControlValue(), - ((UIDescription)child).getText()); - } - else if (child instanceof UIDescriptions) - { - // retrieve the object being pointed to and get - // the descriptions from that - renderDescriptions(context, (UIDescriptions)child); - } - } - } - - /** - * @see javax.faces.component.UIComponent#encodeEnd(javax.faces.context.FacesContext) - */ - public void encodeEnd(FacesContext context) throws IOException - { - // don't need to do anything - } - - /** - * @see javax.faces.component.UIComponent#getRendersChildren() - */ - public boolean getRendersChildren() - { - return true; - } - - /** - * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object) - */ - public void restoreState(FacesContext context, Object state) - { - Object values[] = (Object[])state; - // standard component attributes are restored by the super class - super.restoreState(context, values[0]); - this.selected = (String)values[1]; - } - - /** - * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext) - */ - public Object saveState(FacesContext context) - { - Object values[] = new Object[2]; - // standard component attributes are saved by the super class - values[0] = super.saveState(context); - values[1] = this.selected; - return (values); - } - - /** - * Renders a description item - * - * @param context The faces context - * @param controlId The id of the control the description is for - * @param text The description text - */ - private void renderDescription(FacesContext context, String controlId, String text) - throws IOException - { - ResponseWriter out = context.getResponseWriter(); - out.write(""); - out.write(Utils.encode(text)); - out.write("\n"); - } - - /** - * Renders the given descriptions component - * - * @param context The faces context - * @param descriptions The descriptions to render - */ - @SuppressWarnings("unchecked") - private void renderDescriptions(FacesContext context, UIDescriptions descriptions) - throws IOException - { - // get hold of the object holding the descriptions and make sure - // it is of the correct type - Object obj = descriptions.getValue(); - - if (obj instanceof Map) - { - Map items = (Map)obj; - for (String id : items.keySet()) - { - renderDescription(context, id, items.get(id)); - } - } - else if (obj instanceof List) - { - Iterator iter = ((List)obj).iterator(); - while (iter.hasNext()) - { - UIDescription desc = (UIDescription)iter.next(); - renderDescription(context, desc.getControlValue(), desc.getText()); - } - } - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/evaluator/BaseEvaluator.java b/war/src/main/java/org/alfresco/web/ui/common/component/evaluator/BaseEvaluator.java deleted file mode 100644 index fed442e478..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/evaluator/BaseEvaluator.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.evaluator; - -import java.io.IOException; - -import javax.faces.context.FacesContext; -import javax.faces.el.ValueBinding; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.extensions.webscripts.ui.common.component.SelfRenderingComponent; - -/** - * @author kevinr - */ -public abstract class BaseEvaluator extends SelfRenderingComponent -{ - /** - * @see javax.faces.component.UIComponent#getFamily() - */ - public final String getFamily() - { - return "org.alfresco.faces.evaluators"; - } - - /** - * @see javax.faces.component.UIComponentBase#getRendersChildren() - */ - public final boolean getRendersChildren() - { - return !evaluate(); - } - - /** - * @see javax.faces.component.UIComponentBase#encodeBegin(javax.faces.context.FacesContext) - */ - public final void encodeBegin(FacesContext context) throws IOException - { - // no output for this component - } - - /** - * @see javax.faces.component.UIComponentBase#encodeChildren(javax.faces.context.FacesContext) - */ - public final void encodeChildren(FacesContext context) throws IOException - { - // if this is called, then the evaluate returned false which means - // the child components show not be allowed to render themselves - } - - /** - * @see javax.faces.component.UIComponentBase#encodeEnd(javax.faces.context.FacesContext) - */ - public final void encodeEnd(FacesContext context) throws IOException - { - // no output for this component - } - - /** - * Get the value for this component to be evaluated against - * - * @return the value for this component to be evaluated against - */ - public Object getValue() - { - ValueBinding vb = getValueBinding("value"); - if (vb != null) - { - this.value = vb.getValue(getFacesContext()); - } - - return this.value; - } - - /** - * Set the value for this component to be evaluated against - * - * @param value the value for this component to be evaluated against - */ - public void setValue(Object value) - { - this.value = value; - } - - /** - * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object) - */ - public void restoreState(FacesContext context, Object state) - { - Object values[] = (Object[])state; - // standard component attributes are restored by the super class - super.restoreState(context, values[0]); - this.value = values[1]; - } - - /** - * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext) - */ - public Object saveState(FacesContext context) - { - Object values[] = new Object[2]; - // standard component attributes are saved by the super class - values[0] = super.saveState(context); - values[1] = this.value; - return (values); - } - - /** - * Evaluate against the component attributes. Return true to allow the inner - * components to render, false to hide them during rendering. - * - * @return true to allow rendering of child components, false otherwise - */ - public abstract boolean evaluate(); - - - protected static final Log s_logger = LogFactory.getLog(BaseEvaluator.class); - - /** the value to be evaluated against */ - private Object value; -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/evaluator/BooleanEvaluator.java b/war/src/main/java/org/alfresco/web/ui/common/component/evaluator/BooleanEvaluator.java deleted file mode 100644 index 09a6e22ab1..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/evaluator/BooleanEvaluator.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.evaluator; - -/** - * @author kevinr - * - * Evaluates to true if the value suppied is a boolean string of "true". - */ -public class BooleanEvaluator extends BaseEvaluator -{ - /** - * Evaluate against the component attributes. Return true to allow the inner - * components to render, false to hide them during rendering. - * - * @return true to allow rendering of child components, false otherwise - */ - public boolean evaluate() - { - boolean result = false; - - try - { - if (getValue() instanceof Boolean) - { - result = ((Boolean)getValue()).booleanValue(); - } - else - { - result = Boolean.valueOf((String)getValue()).booleanValue(); - } - } - catch (Exception err) - { - // return default value on error - s_logger.debug("Unable to evaluate value to boolean: " + getValue()); - } - - return result; - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/evaluator/StringEqualsEvaluator.java b/war/src/main/java/org/alfresco/web/ui/common/component/evaluator/StringEqualsEvaluator.java deleted file mode 100644 index eb4fc0e155..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/evaluator/StringEqualsEvaluator.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.evaluator; - -import javax.faces.context.FacesContext; -import javax.faces.el.ValueBinding; - -/** - * @author kevinr - * - * Evaluates to true if the value exactly matches the supplied string condition. - */ -public class StringEqualsEvaluator extends BaseEvaluator -{ - /** - * Evaluate against the component attributes. Return true to allow the inner - * components to render, false to hide them during rendering. - * - * @return true to allow rendering of child components, false otherwise - */ - public boolean evaluate() - { - boolean result = false; - - try - { - result = getCondition().equals((String)getValue()); - } - catch (Exception err) - { - // return default value on error - s_logger.debug("Expected String value for evaluation: " + getValue()); - } - - return result; - } - - /** - * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object) - */ - public void restoreState(FacesContext context, Object state) - { - Object values[] = (Object[])state; - // standard component attributes are restored by the super class - super.restoreState(context, values[0]); - this.condition = (String)values[1]; - } - - /** - * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext) - */ - public Object saveState(FacesContext context) - { - Object values[] = new Object[2]; - // standard component attributes are saved by the super class - values[0] = super.saveState(context); - values[1] = this.condition; - return (values); - } - - /** - * Get the string condition to match value against - * - * @return the string condition to match value against - */ - public String getCondition() - { - ValueBinding vb = getValueBinding("condition"); - if (vb != null) - { - this.condition = (String)vb.getValue(getFacesContext()); - } - - return this.condition; - } - - /** - * Set the string condition to match value against - * - * @param condition string condition to match value against - */ - public void setCondition(String condition) - { - this.condition = condition; - } - - - /** the string condition to match value against */ - private String condition = null; -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/component/evaluator/ValueSetEvaluator.java b/war/src/main/java/org/alfresco/web/ui/common/component/evaluator/ValueSetEvaluator.java deleted file mode 100644 index 7300e83969..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/component/evaluator/ValueSetEvaluator.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.component.evaluator; - -/** - * @author kevinr - * - * Evaluates to true if the value supplied is not null. - */ -public class ValueSetEvaluator extends BaseEvaluator -{ - /** - * Evaluate against the component attributes. Return true to allow the inner - * components to render, false to hide them during rendering. - * - * @return true to allow rendering of child components, false otherwise - */ - public boolean evaluate() - { - return getValue() != null ? true : false; - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/converter/BooleanLabelConverter.java b/war/src/main/java/org/alfresco/web/ui/common/converter/BooleanLabelConverter.java deleted file mode 100644 index e6308f71e2..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/converter/BooleanLabelConverter.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.converter; - -import java.util.Collection; -import java.util.ResourceBundle; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.convert.Converter; -import javax.faces.convert.ConverterException; - -import org.alfresco.web.app.Application; - -/** - * Converter class to convert a Boolean value (including null) into a human readable form. - * - * @author Kevin Roast - */ -public class BooleanLabelConverter implements Converter -{ - /** - *

The standard converter id for this converter.

- */ - public static final String CONVERTER_ID = "org.alfresco.faces.BooleanLabelConverter"; - - private static final String MSG_YES = "yes"; - private static final String MSG_NO = "no"; - - /** - * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.String) - */ - public Object getAsObject(FacesContext context, UIComponent component, String value) - throws ConverterException - { - return Boolean.valueOf(value); - } - - /** - * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object) - */ - public String getAsString(FacesContext context, UIComponent component, Object value) - throws ConverterException - { - ResourceBundle bundle = Application.getBundle(context); - - String result = bundle.getString(MSG_NO); - - if (value instanceof Boolean) - { - result = ((Boolean)value).booleanValue() ? bundle.getString(MSG_YES) : bundle.getString(MSG_NO); - } - else if (value instanceof Collection) - { - StringBuilder buffer = new StringBuilder(); - for (Object obj : (Collection)value) - { - if (buffer.length() != 0) - { - buffer.append(", "); - } - - if (obj instanceof Boolean) - { - buffer.append(((Boolean)obj).booleanValue() ? - bundle.getString(MSG_YES) : bundle.getString(MSG_NO)); - } - else - { - buffer.append(obj.toString()); - } - } - - result = buffer.toString(); - } - - return result; - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/converter/ByteSizeConverter.java b/war/src/main/java/org/alfresco/web/ui/common/converter/ByteSizeConverter.java deleted file mode 100644 index b388d64e66..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/converter/ByteSizeConverter.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.converter; - -import java.text.DecimalFormat; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.convert.Converter; - -import org.alfresco.web.app.Application; - -/** - * Converter class to convert the size of an item in bytes into a readable KB/MB form. - * - * @author Kevin Roast - */ -public class ByteSizeConverter implements Converter -{ - /** - *

The standard converter id for this converter.

- */ - public static final String CONVERTER_ID = "org.alfresco.faces.ByteSizeConverter"; - - private static final String MSG_POSTFIX_KB = "kilobyte"; - private static final String MSG_POSTFIX_MB = "megabyte"; - private static final String MSG_POSTFIX_GB = "gigabyte"; - - private static final String NUMBER_PATTERN = "###,###.##"; - - /** - * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.String) - */ - public Object getAsObject(FacesContext context, UIComponent component, String value) - { - return Long.parseLong(value); - } - - /** - * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object) - */ - public String getAsString(FacesContext context, UIComponent component, Object value) - { - long size; - if (value instanceof Long) - { - size = (Long)value; - } - else if (value instanceof String) - { - try - { - size = Long.parseLong((String)value); - } - catch (NumberFormatException ne) - { - return (String)value; - } - } - else - { - return ""; - } - - // get formatter - // TODO: can we cache this instance...? DecimalFormat is not threadsafe! Need threadlocal instance. - DecimalFormat formatter = new DecimalFormat(NUMBER_PATTERN); - - StringBuilder buf = new StringBuilder(); - - if (size < 999999) - { - double val = ((double)size) / 1024.0; - buf.append(formatter.format(val)) - .append(' ') - .append(Application.getMessage(context, MSG_POSTFIX_KB)); - } - else if (size < 999999999) - { - double val = ((double)size) / 1048576.0; - buf.append(formatter.format(val)) - .append(' ') - .append(Application.getMessage(context, MSG_POSTFIX_MB)); - } - else - { - double val = ((double)size) / 1073741824.0; - buf.append(formatter.format(val)) - .append(' ') - .append(Application.getMessage(context, MSG_POSTFIX_GB)); - } - - return buf.toString(); - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/converter/MultiValueConverter.java b/war/src/main/java/org/alfresco/web/ui/common/converter/MultiValueConverter.java deleted file mode 100644 index 636efcfc24..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/converter/MultiValueConverter.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.converter; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.StringTokenizer; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.convert.Converter; -import javax.faces.convert.ConverterException; - -/** - * Converter class to convert a List of multiple values into a comma - * separated list. - * - * @author gavinc - */ -public class MultiValueConverter implements Converter -{ - /** - *

The standard converter id for this converter.

- */ - public static final String CONVERTER_ID = "org.alfresco.faces.MultiValueConverter"; - - /** - * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.String) - */ - public Object getAsObject(FacesContext context, UIComponent component, String value) - throws ConverterException - { - List items = new ArrayList(); - StringTokenizer tokenizer = new StringTokenizer(value, ", "); - while (tokenizer.hasMoreTokens()) - { - items.add(tokenizer.nextToken().trim()); - } - - return items; - } - - /** - * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object) - */ - public String getAsString(FacesContext context, UIComponent component, Object value) - throws ConverterException - { - String result = null; - - if (value instanceof Collection) - { - StringBuilder buffer = new StringBuilder(); - for (Object obj : (Collection)value) - { - if (buffer.length() != 0) - { - buffer.append(", "); - } - - buffer.append(obj.toString()); - } - - result = buffer.toString(); - } - else if (value != null) - { - result = value.toString(); - } - - return result; - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/converter/XMLDateConverter.java b/war/src/main/java/org/alfresco/web/ui/common/converter/XMLDateConverter.java deleted file mode 100644 index 82a78a8991..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/converter/XMLDateConverter.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.converter; - -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.TimeZone; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.convert.DateTimeConverter; - -import org.springframework.extensions.surf.util.ISO8601DateFormat; - -/** - * Converter class to convert an XML date representation into a Date - * - * @author gavinc - */ -public class XMLDateConverter extends DateTimeConverter -{ - /** - *

The standard converter id for this converter.

- */ - public static final String CONVERTER_ID = "org.alfresco.faces.XMLDateConverter"; - - /** - * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.String) - */ - public Object getAsObject(FacesContext context, UIComponent component, String value) - { - return ISO8601DateFormat.parse(value); - } - - /** - * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object) - */ - public String getAsString(FacesContext context, UIComponent component, Object value) - { - String str = null; - - if (value instanceof String) - { - Date date = ISO8601DateFormat.parse((String)value); - str = super.getAsString(context, component, date); - } - else if (value instanceof List) - { - StringBuilder buffer = new StringBuilder(); - for (Object date : ((List)value)) - { - if (buffer.length() != 0) - { - buffer.append(", "); - } - - buffer.append(super.getAsString(context, component, date)); - } - - str = buffer.toString(); - } - else - { - str = super.getAsString(context, component, value); - } - - return str; - } - - /** - * @see javax.faces.convert.DateTimeConverter#getTimeZone() - */ - @Override - public TimeZone getTimeZone() - { - // Note: this forces the display of the date to the server's timezone - it does not - // take into account any client specific timezone - return TimeZone.getDefault(); - } - - /** - * @see javax.faces.convert.DateTimeConverter#getLocale() - */ - @Override - public Locale getLocale() - { - // get the locale set in the client - FacesContext context = FacesContext.getCurrentInstance(); - Locale locale = context.getViewRoot().getLocale(); - if (locale == null) - { - // else use server locale as the default - locale = Locale.getDefault(); - } - - return locale; - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/renderer/ActionLinkRenderer.java b/war/src/main/java/org/alfresco/web/ui/common/renderer/ActionLinkRenderer.java deleted file mode 100644 index 3c10da0dca..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/renderer/ActionLinkRenderer.java +++ /dev/null @@ -1,445 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.renderer; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.io.Writer; -import java.net.URLEncoder; -import java.util.Map; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; - -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.UIActionLink; -import org.alfresco.web.ui.common.component.UIMenu; -import org.alfresco.web.ui.repo.component.UIActions; - -/** - * @author kevinr - */ -public class ActionLinkRenderer extends BaseRenderer -{ - // ------------------------------------------------------------------------------ - // Renderer implementation - - /** - * @see javax.faces.render.Renderer#decode(javax.faces.context.FacesContext, javax.faces.component.UIComponent) - */ - public void decode(FacesContext context, UIComponent component) - { - Map requestMap = context.getExternalContext().getRequestParameterMap(); - String fieldId = Utils.getActionHiddenFieldName(context, component); - String value = (String)requestMap.get(fieldId); - // we are clicked if the hidden field contained our client id - if (value != null && value.equals(component.getClientId(context))) - { - // get all the params for this actionlink, see if any values have been set - // on the request which match our params and set them into the component - UIActionLink link = (UIActionLink)component; - Map destParams = link.getParameterMap(); - Map actionParams = getParameterComponents(link); - if (actionParams != null) - { - for (String name : actionParams.keySet()) - { - String paramValue = (String)requestMap.get(name); - destParams.put(name, paramValue); - } - } - - ActionEvent event = new ActionEvent(component); - component.queueEvent(event); - } - } - - /** - * @see javax.faces.render.Renderer#encodeEnd(javax.faces.context.FacesContext, javax.faces.component.UIComponent) - */ - public void encodeEnd(FacesContext context, UIComponent component) throws IOException - { - // always check for this flag - as per the spec - if (!component.isRendered()) - { - return; - } - - UIActionLink link = (UIActionLink)component; - - // if there is no value for the link there will be no visible output - // on the page so don't bother rendering anything - if (link.getValue() != null) - { - Writer out = context.getResponseWriter(); - - UIComponent verticalContiner = getVerticalContainer(link); - if (verticalContiner != null) - { - int padding = link.getPadding(); - - if (verticalContiner instanceof UIActions) - { - padding = ((UIActions)verticalContiner).getVerticalSpacing(); - } - // render as menu item style action link - renderMenuAction(context, out, link, padding); - } - else - { - // render as action link - renderActionLink(context, out, link); - } - } - } - - /** - * Render ActionLink as plain link and image - * - * @param context FacesContext - * @param out Writer - * @param link UIActionLink - */ - private void renderActionLink(FacesContext context, Writer out, UIActionLink link) - throws IOException - { - // output the action link - with an image icon if specified, else just the text link part - String image = link.getImage(); - if (image != null) - { - int padding = link.getPadding(); - if (padding != 0) - { - // TODO: make this width value a property! - out.write("
"); - } - - // if we are not show the text link, then the image is the clickable element - if (link.getShowLink() == false) - { - renderActionLinkAnchor(context, out, link); - } - - String verticalAlign = link.getVerticalAlign(); - out.write(Utils.buildImageTag( - context, image, ((null != link.getTooltip()) ? (link.getTooltip()):(String)link.getValue()), verticalAlign == null ? "-4px" : verticalAlign)); - - if (link.getShowLink() == false) - { - out.write(""); - } - else - { - if (padding != 0) - { - out.write(""); - } - - // else the text is the clickable element - renderActionLinkAnchor(context, out, link); - out.write(Utils.encode(link.getValue().toString())); - out.write(""); - } - - if (padding != 0) - { - out.write("
"); - } - } - else - { - // no image, so text is the clickable element - renderActionLinkAnchor(context, out, link); - out.write(Utils.encode(link.getValue().toString())); - out.write(""); - } - } - - /** - * Render ActionLink as plain link and image - * - * @param context FacesContext - * @param out Writer - * @param link UIActionLink - */ - private void renderActionLinkAnchor(final FacesContext context, - final Writer out, - final UIActionLink link) - throws IOException - { - final Map attrs = link.getAttributes(); - - // generate the href link - output later in the process depending on various rendering options - if (link.getHref() == null) - { - out.write(""); - - out.write(""); - } - - - // ------------------------------------------------------------------------------ - // Private helpers - - /** - * Return any vertically rendered container component the action link is present within - * - * @param link The ActionLink to test - * - * @return UIComponent vertically rendered component - */ - private static UIComponent getVerticalContainer(UIActionLink link) - { - UIComponent parent = link.getParent(); - while (parent != null) - { - if (parent instanceof UIMenu || - (parent instanceof UIActions && ((UIActions)parent).getVerticalSpacing() != 0)) - { - break; - } - parent = parent.getParent(); - } - return parent; - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/renderer/BaseRenderer.java b/war/src/main/java/org/alfresco/web/ui/common/renderer/BaseRenderer.java deleted file mode 100644 index 302448386d..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/renderer/BaseRenderer.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.renderer; - -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.component.UIComponent; -import javax.faces.component.UIParameter; -import javax.faces.context.FacesContext; -import javax.faces.context.ResponseWriter; -import javax.faces.render.Renderer; - -/** - * Base renderer class. Contains helper methods to assist most renderers. - * - * @author kevinr - */ -public abstract class BaseRenderer extends Renderer -{ - /** - * Helper to output an attribute to the output stream - * - * @param out ResponseWriter - * @param attr attribute value object (cannot be null) - * @param mapping mapping to output as e.g. style="..." - * - * @throws IOException - */ - protected static void outputAttribute(ResponseWriter out, Object attr, String mapping) - throws IOException - { - if (attr != null) - { - out.write(' '); - out.write(mapping); - out.write("=\""); - out.write(attr.toString()); - out.write('"'); - } - } - - /** - * Ensures that the given context and component are not null. This method - * should be called by all renderer methods that are given these parameters. - * - * @param ctx Faces context - * @param component The component - */ - protected static void assertParmeters(FacesContext ctx, UIComponent component) - { - if (ctx == null) - { - throw new IllegalStateException("context can not be null"); - } - - if (component == null) - { - throw new IllegalStateException("component can not be null"); - } - } - - /** - * Return the map of name/value pairs for any child UIParameter components. - * - * @param component to find UIParameter child values for - * - * @return a Map of name/value pairs or null if none found - */ - protected static Map getParameterComponents(final UIComponent component) - { - if (component.getChildCount() == 0) - { - return null; - } - - final Map params = new HashMap(component.getChildCount(), 1.0f); - for (UIComponent child : (List)component.getChildren()) - { - if (child instanceof UIParameter) - { - final UIParameter param = (UIParameter)child; - params.put(param.getName(), param.getValue() != null ? param.getValue().toString() : null); - } - } - return params; - } -} diff --git a/war/src/main/java/org/alfresco/web/ui/common/renderer/BreadcrumbRenderer.java b/war/src/main/java/org/alfresco/web/ui/common/renderer/BreadcrumbRenderer.java deleted file mode 100644 index 02c3b1dbca..0000000000 --- a/war/src/main/java/org/alfresco/web/ui/common/renderer/BreadcrumbRenderer.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * #%L - * Alfresco Repository WAR Community - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.web.ui.common.renderer; - -import java.io.IOException; -import java.io.Writer; -import java.util.List; -import java.util.Map; - -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; - -import org.alfresco.web.ui.common.Utils; -import org.alfresco.web.ui.common.component.IBreadcrumbHandler; -import org.alfresco.web.ui.common.component.UIBreadcrumb; - -/** - * Renderer class for the UIBreadcrumb component - * - * @author Kevin Roast - */ -public class BreadcrumbRenderer extends BaseRenderer -{ - // ------------------------------------------------------------------------------ - // Renderer implementation - - /** - * @see javax.faces.render.Renderer#decode(javax.faces.context.FacesContext, javax.faces.component.UIComponent) - */ - public void decode(FacesContext context, UIComponent component) - { - Map requestMap = context.getExternalContext().getRequestParameterMap(); - String fieldId = getHiddenFieldName(context, component); - String value = (String)requestMap.get(fieldId); - if (value != null && value.length() != 0) - { - // create a breadcrumb specific action event if we were clicked - int selectedIndex = Integer.parseInt(value); - UIBreadcrumb.BreadcrumbEvent event = new UIBreadcrumb.BreadcrumbEvent(component, selectedIndex); - component.queueEvent(event); - } - } - - /** - * @see javax.faces.render.Renderer#encodeBegin(javax.faces.context.FacesContext, javax.faces.component.UIComponent) - */ - public void encodeBegin(FacesContext context, UIComponent component) throws IOException - { - // always check for this flag - as per the spec - if (component.isRendered() == true) - { - Writer out = context.getResponseWriter(); - - UIBreadcrumb breadcrumb = (UIBreadcrumb)component; - // get the List of IBreadcrumbHandler elements from the component - List elements = (List)breadcrumb.getValue(); - - boolean first = true; - for (int index=0; index