Dritter (letzter) Teil der neuen Installationsroutine. Es ist mit ccm-hostinit nun möglich, Packages hinzu zu fügen einschl. mergen von web.xml, und dann in einem 2. Schritt mit load in die Datenbank zu laden.

git-svn-id: https://svn.libreccm.org/ccm/trunk@1091 8810af33-2d31-482b-a856-94f89814c4df
master
pb 2011-09-04 15:23:34 +00:00
parent 6bf79afad2
commit 72eebe2e13
120 changed files with 14917 additions and 75 deletions

View File

@ -14,36 +14,6 @@
# PATH, you have to adjust the paths.
CCM_LIB_DIR="../lib"
CCM_HOME_DIR="../.."
# echo "CCM_LIB_DIR is " ${CCM_LIB_DIR}
# echo "CCM_HOME_DIR is " ${CCM_HOME_DIR}
# We need CATALINA_HOME environment variable to access Tomcat's lib dir.
#if [[ -z "$CATALINA_HOME" ]] ; then
# echo CATALINE_HOME not set. Guessing ...
# if [ -f /etc/tomcat6/tomcat6.conf ]
# then
# . /etc/tomcat6/tomcat6.conf
# echo
# echo Using CATALINA_HOME = $CATALINA_HOME
# echo If this doesn\'t work use
# echo export CATALINA_HOME=/path/to/tomcat/installation
# echo to point us to the correct location.
# else
# echo
# echo ===================================================
# echo Environment variable CATALINA_HOME not set. We need
# echo to know the location of Tomcat\'s lib directory.
# echo So use
# echo export CATALINA_HOME=/path/to/tomcat/installation
# echo to point us to the correct location and run ccm
# echo again.
# echo ===================================================
# echo
# exit 1
# fi
#fi
#CATALINA_LIB_DIR="${CATALINA_HOME}/lib"
# We need CCM_REPO environment variable to access the source dir.
if [[ -z "$CCM_REPO" ]] ; then
@ -73,7 +43,7 @@ if [[ -z "$CCM_REPO" ]] ; then
echo " export CCM_REPO=/path/to/repo "
echo to point us to the correct location and run
echo ccm-hostinit again or execute
echo " CCM_REPO=/path/to/repo ccm-hostinit [task] "
echo " CCM_REPO=/path/to/repo sh ccm-hostinit [task] "
echo again
echo ===================================================
echo
@ -97,26 +67,24 @@ then
exit 1
fi
#if [ ! -f ${CATALINA_LIB_DIR}/catalina.jar ]
#then
# echo "Error: CATALINA_LIB_DIR is invalid \(no catalina.jar in CATALINA_LIB_DIR\)."
# exit 1
#fi
#Convert to absolute path:
CCM_HOME=`cd ${CCM_HOME_DIR}; pwd`
# echo "CCM_HOME_DIR: " ${CCM_HOME_DIR}
# echo "PARAMETER before shift: " "$@"
ANT_HOME_DIR="./libexec/ant"
ANT_HOME=`cd ${ANT_HOME_DIR}; pwd`
export ANT_HOME
# echo "ANT_HOME: " ${ANT_HOME}
# echo "Starting CCM-Tool..."
# java -cp ${CCM_LIB_DIR}/"*":${CATALINA_LIB_DIR}/"*" -Dccm.home=${CCM_HOME_DIR} "com.arsdigita.packaging.MasterTool" "$@"
TASK="$1"
# shift
shift
# echo "PARAMETER after shift: " "$@"
PACKAGES="$@" ${PACKAGES}
# echo "Packages: " ${PACKAGES}
exec libexec/ant/bin/ant ${TASK} -quiet -f libexec/build.xml -Dccm.home.dir=${CCM_HOME} -Dccm.repo.dir=${CCM_REPO} -Dccm.packages="${PACKAGES}"
if [ "$1" = "--packagefile" ]
then
# Absolute path of current dir
MY_DIR=`pwd`
# Construct absolute (canonical) filename
FILENAME=${MY_DIR}/$2
exec libexec/ant/bin/ant ${TASK} -quiet -f libexec/build.xml -Dccm.home.dir=${CCM_HOME} -Dccm.repo.dir=${CCM_REPO} -Dccm.packages.filename="${FILENAME}"
else
PACKAGES="$@"
exec libexec/ant/bin/ant ${TASK} -quiet -f libexec/build.xml -Dccm.home.dir=${CCM_HOME} -Dccm.repo.dir=${CCM_REPO} -Dccm.packages="${PACKAGES}"
fi

Binary file not shown.

Binary file not shown.

View File

@ -22,7 +22,10 @@
<description>HostInit deploys CCM into a servlet container. Specifically it deploys
ADDON packages.
</description>
<taskdef resource="net/sf/antcontrib/antcontrib.properties"/>
<taskdef resource="net/sf/antcontrib/antcontrib.properties"/>
<taskdef name="webxmlmerge"
classname="com.arsdigita.ant.WebXMLMergeTask"
classpath="webxml-mergetool.jar"/>
<!-- base directory of the development environment
default is parent directory of build.xml (sysprop basedir) -->
@ -44,59 +47,132 @@
<echo message="Packages available:" />
<echo message="===================" />
<echo message=" " />
<echo message="${prop.repo.filelist}"/>
<echo message="${prop.repo.filelist}"/>
</target>
<target name="add" depends="init">
<echo>Packages requested: ${ccm.packages} </echo>
<echo message="Packages requested: ${ccm.requested.packages}" />
<echo message=" " />
<foreach target="copy-dir"
param="dirname"
list="${ccm.packages}"
<foreach target="copy-package"
param="packagename"
list="${ccm.requested.packages}"
delimiter=" " />
</target>
<target name="copy-dir" >
<target name="copy-package" depends="package-notInstalled,package-dependenciesOK" >
<echo> Package working on: ${dirname} </echo>
<echo>Package working on: ${packagename} </echo>
<copy todir="${ccm.home.dir}"
overwrite="true"
includeEmptyDirs="true"
failonerror="false"
verbose="true" >
<fileset dir="${ccm.repo.dir}/${dirname}/web" />
<fileset dir="${ccm.repo.dir}/${packagename}/web" />
</copy>
<copy todir="${ccm.home.dir}/WEB-INF/lib"
overwrite="true"
includeEmptyDirs="true"
failonerror="false"
verbose="true" >
<fileset dir="${ccm.repo.dir}/${dirname}" includes="*.jar" />
<fileset dir="${ccm.repo.dir}/${packagename}" includes="*.jar" />
</copy>
<copy todir="${ccm.home.dir}/WEB-INF/lib"
overwrite="true"
includeEmptyDirs="true"
failonerror="false"
verbose="true" >
<fileset dir="${ccm.repo.dir}/${dirname}/lib" />
<fileset dir="${ccm.repo.dir}/${packagename}/lib" />
</copy>
<if>
<resourceexists>
<file file="${ccm.repo.dir}/${packagename}/web/WEB-INF/web.${packagename}.xml"/>
</resourceexists>
<then>
<echo message="Merging web.${packagename}.xml" />
<webxmlmerge originalfile="${ccm.home.dir}/WEB-INF/web.xml"
mergefile="${ccm.repo.dir}/${packagename}/web/WEB-INF/web.${packagename}.xml"
destfile="${ccm.home.dir}/WEB-INF/.merged.web.xml" />
<copy file="${ccm.home.dir}/WEB-INF/.merged.web.xml"
tofile="${ccm.home.dir}/WEB-INF/web.xml"
overwrite="yes"/>
<delete file="${ccm.home.dir}/WEB-INF/.merged.web.xml"/>
</then>
<else>
<echo message="No web.xml fragment to merge." />
</else>
</if>
<echo>Installation of package ${packagename} completed. </echo>
<echo message=" " />
</target>
<target name="package-notInstalled" depends="init">
<!-- Target will fail and abort build if parameter packagename
is already installed in property war.packages.config -->
<fail message="${packagename} already installed! " >
<condition >
<matches string="${waf.config.packages}"
pattern="${packagename}" />
</condition>
</fail>
</target>
<target name="package-dependenciesOK" depends="init">
<!-- Target will fail and abort build if parameter packagename
has dependencies which are not already installed.
Each package must have at least 1 dependency: ccm-core. -->
<xmlproperty file="${ccm.repo.dir}/${packagename}/application.xml"
collapseAttributes="true" />
<fail message="${packagename} has no requirements defined. Contact developer!"
unless="ccm:application.ccm:dependencies.ccm:requires.name" />
<echo message="Checking dependencies for ${packagename}" />
<foreach target="package-dependencyCheck"
param="requirement"
list="${ccm:application.ccm:dependencies.ccm:requires.name}"
delimiter="," />
</target>
<target name="package-dependencyCheck" depends="init">
<fail message="${requirement} not installed nor in installation list! " >
<condition >
<not>
<or>
<matches string="${waf.config.packages}"
pattern="${packagename}" />
<matches string="${ccm.requested.packages}"
pattern="${packagename}" />
</or>
</not>
</condition>
</fail>
<echo message="Requirement ${requirement} fullfilled." />
</target>
<target name="info" depends="init">
<echo>Info requested for Package(s): </echo>
<echo>${ccm.packages} </echo>
<echo>${ccm.requested.packages}</echo>
<foreach target="show-info"
param="dirname"
list="${ccm.packages}"
param="packagename"
list="${ccm.requested.packages}"
delimiter=" " />
</target>
@ -105,9 +181,10 @@
<!-- for debugging
<echo> Package working on: ${dirname} </echo> -->
<xmlproperty file="${ccm.repo.dir}/${dirname}/application.xml"
<xmlproperty file="${ccm.repo.dir}/${packagename}/application.xml"
collapseAttributes="true" />
<echo message=" " />
<echo message="${ccm:application.name}: ${ccm:application.prettyName}" />
<echo message="================================================================" />
<echo message=" " />
@ -120,9 +197,13 @@
<target name="init">
<!-- Initialisation task: Sets initial values for several properties, checks
existence of required properties or system values, checks and evaluates
command line parameters. -->
<!-- root project dir (where build.xml lives, WEB-INF/bin/libexec by default -->
<property name="ccm.project.dir" value="${basedir}" />
<!-- Debugging only
<echo message="Project base directory is ${ccm.project.dir} "/> -->
<!-- Check for required variables -->
<!-- Property ccm.home.dir must be defined by invoking script! -->
<fail message="ccm.home.dir or CCM_HOME_DIR not set.
@ -132,18 +213,44 @@
<fail message="ccm.repo.dir or CCM_REPO_DIR not set.
Please check the configuration."
unless="ccm.repo.dir" />
<!-- Property ccm.packages must be defined by invoking script!
May be empty. -->
<fail message="ccm.packages not set.
Please check input and configuration."
unless="ccm.packages" />
<!-- For debugging uncomment
<echoproperties prefix="ccm." />
<echoproperties prefix="ant." /> -->
<if>
<isset property="ccm.packages.filename" />
<then>
<!-- <echo message="Processing file ${ccm.packages.filename}" /> -->
<loadfile property="ccm.requested.packages"
srcFile="${ccm.packages.filename}" >
<!-- Probably a bug in loadfile: Without striplinebreak an addional
(empty) element is added to the property -->
<filterchain>
<striplinebreaks/>
</filterchain>
</loadfile>
<fail message="File ${ccm.packages.filename} not valid."
unless="ccm.requested.packages" />
</then>
<else>
<!-- Property ccm.packages must be defined by invoking script
if no file for package list is definded. May be empty. -->
<fail message="ccm.packages not set.
Please check input and configuration."
unless="ccm.packages" />
<property name="ccm.requested.packages" value="${ccm.packages}" />
</else>
</if>
<!-- Registry for waf.config.packages must exist. -->
<property file="../../conf/registry/registry.properties"/>
<fail message="Registry not found. Guess: try to use 'ccm prepare' first."
unless="waf.config.packages" />
</target>
<target name="usage">
<echo>
Base directory is ${basedir}

View File

@ -0,0 +1,157 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- ANT build file which copies CCM addon packages into an deployed CCM application
and thus extends its functionality.
It checks for package dependencies, and installation consistency (e.g. completes
the web.xml file if necessary.
TASKS (targets):
list lists avaiblable addon packages in source repo.
add {packagelist} adds one or more packages to the aplaws application directory.
info {package} displays info about a package (from package's application.xml).
-->
<!-- Required variables:
ccm.home.dir: base dir of the web application (document root)
Example: /srv/aplaws/webapps/ROOT
Target of deployment
ccm.repo.dir: base dir where ccm packages are stored.
Example: /home/aplaws/aplaws-repo
Source of deployment
-->
<project name="CCM Content and Collaboration Management HostInit task " default="usage">
<description>HostInit deploys CCM into a servlet container. Specifically it deploys
ADDON packages.
</description>
<taskdef resource="net/sf/antcontrib/antcontrib.properties"/>
<!-- base directory of the development environment
default is parent directory of build.xml (sysprop basedir) -->
<!-- Prefix used to access environment variables, globally visibel -->
<property environment="env"/>
<target name="list" depends="init">
<dirset id="repo.contents" dir="${ccm.repo.dir}" includes="ccm-*"/>
<property name="prop.repo.contents" refid="repo.contents"/>
<propertyregex property="prop.repo.filelist"
input="${prop.repo.contents}"
regexp=";"
replace="${line.separator}"
override="true"
defaultValue="no match"
global="true" />
<echo message=" " />
<echo message="Packages available:" />
<echo message="===================" />
<echo message=" " />
<echo message="${prop.repo.filelist}"/>
</target>
<target name="add" depends="init">
<echo>Packages requested: ${ccm.packages} </echo>
<foreach target="copy-dir"
param="dirname"
list="${ccm.packages}"
delimiter=" " />
</target>
<target name="copy-dir" >
<echo> Package working on: ${dirname} </echo>
<copy todir="${ccm.home.dir}"
overwrite="true"
includeEmptyDirs="true"
failonerror="false"
verbose="true" >
<fileset dir="${ccm.repo.dir}/${dirname}/web" />
</copy>
<copy todir="${ccm.home.dir}/WEB-INF/lib"
overwrite="true"
includeEmptyDirs="true"
failonerror="false"
verbose="true" >
<fileset dir="${ccm.repo.dir}/${dirname}" includes="*.jar" />
</copy>
<copy todir="${ccm.home.dir}/WEB-INF/lib"
overwrite="true"
includeEmptyDirs="true"
failonerror="false"
verbose="true" >
<fileset dir="${ccm.repo.dir}/${dirname}/lib" />
</copy>
</target>
<target name="info" depends="init">
<echo>Info requested for Package(s): </echo>
<echo>${ccm.packages} </echo>
<foreach target="show-info"
param="dirname"
list="${ccm.packages}"
delimiter=" " />
</target>
<target name="show-info" >
<!-- for debugging
<echo> Package working on: ${dirname} </echo> -->
<xmlproperty file="${ccm.repo.dir}/${dirname}/application.xml"
collapseAttributes="true" />
<echo message="${ccm:application.name}: ${ccm:application.prettyName}" />
<echo message="================================================================" />
<echo message=" " />
<echo message="${ccm:application.ccm:description}" />
<echo message=" " />
<echo message="Requires:" />
<echo message="${ccm:application.ccm:dependencies.ccm:requires.name}" />
</target>
<target name="init">
<property name="ccm.project.dir" value="${basedir}" />
<!-- Debugging only
<echo message="Project base directory is ${ccm.project.dir} "/> -->
<!-- Check for required variables -->
<!-- Property ccm.home.dir must be defined by invoking script! -->
<fail message="ccm.home.dir or CCM_HOME_DIR not set.
Please check the configuration."
unless="ccm.home.dir" />
<!-- Property ccm.repo.dir must be defined by invoking script! -->
<fail message="ccm.repo.dir or CCM_REPO_DIR not set.
Please check the configuration."
unless="ccm.repo.dir" />
<!-- Property ccm.packages must be defined by invoking script!
May be empty. -->
<fail message="ccm.packages not set.
Please check input and configuration."
unless="ccm.packages" />
<!-- For debugging uncomment
<echoproperties prefix="ccm." />
<echoproperties prefix="ant." /> -->
</target>
<target name="usage">
<echo>
Base directory is ${basedir}
USAGE:
ccm-host list lists avaiblable addon packages
ccm-host add {packagelist} adds one or more packages to the aplaws application directory.
ccm-host info {package} displays info about a package.
</echo>
</target>
</project>

View File

@ -0,0 +1,32 @@
========================
BUILD OUTPUT DESCRIPTION
========================
When you build an Java application project that has a main class, the IDE
automatically copies all of the JAR
files on the projects classpath to your projects dist/lib folder. The IDE
also adds each of the JAR files to the Class-Path element in the application
JAR files manifest file (MANIFEST.MF).
To run the project from the command line, go to the dist folder and
type the following:
java -jar "webxml-mergetool.jar"
To distribute this project, zip up the dist folder (including the lib folder)
and distribute the ZIP file.
Notes:
* If two JAR files on the project classpath have the same name, only the first
JAR file is copied to the lib folder.
* Only JAR files are copied to the lib folder.
If the classpath contains other types of files or folders, these files (folders)
are not copied.
* If a library on the projects classpath also has a Class-Path element
specified in the manifest,the content of the Class-Path element has to be on
the projects runtime path.
* To set a main class in a standard Java project, right-click the project node
in the Projects window and choose Properties. Then click Run and enter the
class name in the Main Class field. Alternatively, you can manually type the
class name in the manifest Main-Class element.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,34 @@
webxml-mergetool
Purpose:
Takes an existing web.xml deployment descriptor (original file) and
a web.xml fragment (merge file) and inserts those elements of merge file
which are not already in original file into original file and save the
combined content in destination file.
Usage:
The tool acts as an ANT task.
At beginning of build.xml:
<taskdef name="webxmlmerge"
classname="com.arsdigita.ant.WebXMLMergeTask"
classpath="webxml-mergetool.jar"/>
To use add at appropriate location:
<webxmlmerge originalfile="${ccm.home.dir}/WEB-INF/web.xml"
mergefile="${ccm.repo.dir}/${packagename}/web/WEB-INF/web.${packagename}.xml"
destfile="${ccm.home.dir}/WEB-INF/.merged.web.xml" />
Eventually followed by
<copy file="${ccm.home.dir}/WEB-INF/.merged.web.xml"
tofile="${ccm.home.dir}/WEB-INF/web.xml"
overwrite="yes"/>
<delete file="${ccm.home.dir}/WEB-INF/.merged.web.xml"/>

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,2 @@
libs.CopyLibs.classpath=\
${base}/CopyLibs/org-netbeans-modules-java-j2seproject-copylibstask.jar

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,3 @@
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build

View File

@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- You may freely edit this file. See commented blocks below for -->
<!-- some examples of how to customize the build. -->
<!-- (If you delete it and reopen the project it will be recreated.) -->
<!-- By default, only the Clean and Build commands use this build script. -->
<!-- Commands such as Run, Debug, and Test only use this build script if -->
<!-- the Compile on Save feature is turned off for the project. -->
<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
<!-- in the project's Project Properties dialog box.-->
<project name="webxml-mergetool" default="default" basedir=".">
<description>Builds, tests, and runs the project webxml-mergetool.</description>
<import file="nbproject/build-impl.xml"/>
<!--
There exist several targets which are by default empty and which can be
used for execution of your tasks. These targets are usually executed
before and after some main targets. They are:
-pre-init: called before initialization of project properties
-post-init: called after initialization of project properties
-pre-compile: called before javac compilation
-post-compile: called after javac compilation
-pre-compile-single: called before javac compilation of single file
-post-compile-single: called after javac compilation of single file
-pre-compile-test: called before javac compilation of JUnit tests
-post-compile-test: called after javac compilation of JUnit tests
-pre-compile-test-single: called before javac compilation of single JUnit test
-post-compile-test-single: called after javac compilation of single JUunit test
-pre-jar: called before JAR building
-post-jar: called after JAR building
-post-clean: called after cleaning build products
(Targets beginning with '-' are not intended to be called on their own.)
Example of inserting an obfuscator after compilation could look like this:
<target name="-post-compile">
<obfuscate>
<fileset dir="${build.classes.dir}"/>
</obfuscate>
</target>
For list of available properties check the imported
nbproject/build-impl.xml file.
Another way to customize the build is by overriding existing main targets.
The targets of interest are:
-init-macrodef-javac: defines macro for javac compilation
-init-macrodef-junit: defines macro for junit execution
-init-macrodef-debug: defines macro for class debugging
-init-macrodef-java: defines macro for class execution
-do-jar-with-manifest: JAR building (if you are using a manifest)
-do-jar-without-manifest: JAR building (if you are not using a manifest)
run: execution of project
-javadoc-build: Javadoc generation
test-report: JUnit report generation
An example of overriding the target for project execution could look like this:
<target name="run" depends="webxml-mergetool-impl.jar">
<exec dir="bin" executable="launcher.exe">
<arg file="${dist.jar}"/>
</exec>
</target>
Notice that the overridden target depends on the jar target and not only on
the compile target as the regular run target does. Again, for a list of available
properties which you can use, check the target you are overriding in the
nbproject/build-impl.xml file.
-->
</project>

View File

@ -0,0 +1,225 @@
/*
* Copyright (C) 2011 Peter Boy (pb@zes.uni-bremen.de) All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.arsdigita.ant;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.xml.Document;
import com.liferay.portal.kernel.xml.DocumentException;
import com.liferay.portal.kernel.xml.Element;
import com.liferay.portal.kernel.xml.SAXReaderUtil;
import com.liferay.portal.xml.DocumentImpl;
import com.liferay.portal.xml.SAXReaderImpl;
import com.liferay.util.xml.XMLMerger;
import com.liferay.util.xml.descriptor.WebXML23Descriptor;
import com.liferay.util.xml.descriptor.WebXML24Descriptor;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
// import org.apache.tools.ant.Project;
/**
*
* @author pb
*/
public class WebXMLMergeTask extends Task {
// Instance Variables ------------------------------------------------------
/** Location of the original <code>web.xml</code>. */
private String originalFile;
/** Location of the file to merge in <code>web.xml</code>. */
private String mergeFile;
/** Location of the resulting (destination) <code>web.xml</code>. */
private String destFile;
// Public Methods ----------------------------------------------------------
/**
* {@inheritDoc}
* @see Task#execute()
*/
@Override
public void execute() throws BuildException {
// /* Check parameters */
// if ((this.originalFile == null) || !this.originalFile.isFile())
// {
// throw new BuildException("The [originalfile] attribute is required");
// }
// if (this.mergeFile == null)
// {
// throw new BuildException("The [mergefile] attribute is required");
// }
// if (this.destFile == null)
// {
// throw new BuildException("The [destfile] attribute is required");
// }
BuildWebXML(originalFile, mergeFile, destFile);
}
private void BuildWebXML(String originalWebXML, String customWebXML,
String mergedWebXML) {
try {
String customContent = readFileIntoString(customWebXML);
int x = customContent.indexOf("<web-app");
x = customContent.indexOf(">", x) + 1;
int y = customContent.indexOf("</web-app>");
customContent = customContent.substring(x, y);
String originalContent = readFileIntoString(originalWebXML);
int z = originalContent.indexOf("<web-app");
z = originalContent.indexOf(">", z) + 1;
String mergedContent =
originalContent.substring(0, z) + customContent +
originalContent.substring(z, originalContent.length());
mergedContent = processContent(mergedContent);
writeFileFromString(mergedWebXML, mergedContent);
}
catch (Exception e) {
e.printStackTrace();
}
}
private String processContent(String webXML)
throws DocumentException, IOException {
webXML = stripHtmlComments(webXML);
new SAXReaderUtil().setSAXReader(new SAXReaderImpl());
double version = 2.3;
Document doc = SAXReaderUtil.read(webXML);
Element root = doc.getRootElement();
version = GetterUtil.getDouble(root.attributeValue("version"), version);
XMLMerger merger = null;
if (version == 2.3) {
merger = new XMLMerger(new WebXML23Descriptor());
}
else {
merger = new XMLMerger(new WebXML24Descriptor());
}
DocumentImpl docImpl = (DocumentImpl)doc;
merger.organizeXML(docImpl.getWrappedDocument());
webXML = doc.formattedString();
return webXML;
}
private String readFileIntoString(String filename)
throws IOException {
BufferedReader cbr = new BufferedReader(
new InputStreamReader(
new FileInputStream(filename)));
StringBuilder contentOfFile = new StringBuilder();
String line;
while ((line = cbr.readLine()) != null) {
contentOfFile.append(line);
contentOfFile.append('\n');
}
return(contentOfFile.toString());
}
private void writeFileFromString(String fileName, String content)
throws IOException{
FileOutputStream fos = new FileOutputStream(fileName);
for (int i=0; i < content.length(); i++){
fos.write((byte)content.charAt(i));
}
fos.close();
}
private String stripHtmlComments(String xmlContent) {
String strippedContent = StringUtil.stripBetween(xmlContent,
"<!--", "-->");
return(strippedContent);
}
/**
* The original web deployment descriptor into which the new elements will
* be merged.
*
* @param theSrcFile the original <code>web.xml</code>
*/
public final void setOriginalFile(String originalFile)
{
this.originalFile = originalFile;
}
/**
* The descriptor to merge into the original file.
*
* @param theMergeFile the <code>web.xml</code> to merge
*/
public final void setMergeFile(String mergeFile)
{
this.mergeFile = mergeFile;
}
/**
* The destination file where the result of the merge are stored.
*
* @param theDestFile the resulting <code>web.xml</code>
*/
public final void setDestFile(String destFile)
{
this.destFile = destFile;
}
}

View File

@ -0,0 +1,378 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.io.unsync;
import com.liferay.portal.kernel.util.CharPool;
import com.liferay.portal.kernel.util.StringBundler;
import java.io.IOException;
import java.io.Reader;
/**
* <p>
* See http://issues.liferay.com/browse/LPS-6648.
* </p>
*
* @author Shuyang Zhou
*/
public class UnsyncBufferedReader extends Reader {
public UnsyncBufferedReader(Reader reader) {
this(reader, _DEFAULT_BUFFER_SIZE);
}
public UnsyncBufferedReader(Reader reader, int size) {
this.reader = reader;
buffer = new char[size];
}
public void close() throws IOException {
if (reader != null) {
reader.close();
reader = null;
}
buffer = null;
}
public void mark(int markLimit) throws IOException {
if (reader == null) {
throw new IOException("Reader is null");
}
this.markLimit = markLimit;
markIndex = index;
}
public boolean markSupported() {
return true;
}
public int read() throws IOException {
if (reader == null) {
throw new IOException("Reader is null");
}
if (index >= firstInvalidIndex) {
readUnderlyingReader();
if (index >= firstInvalidIndex) {
return -1;
}
}
return buffer[index++];
}
public int read(char[] charArray) throws IOException {
return read(charArray, 0, charArray.length);
}
public int read(char[] charArray, int offset, int length)
throws IOException {
if (reader == null) {
throw new IOException("Reader is null");
}
if (length <= 0) {
return 0;
}
int read = 0;
while (true) {
int available = firstInvalidIndex - index;
if ((available + read) >= length) {
// Enough data, stop reading
int leftSize = length - read;
System.arraycopy(buffer, index, charArray, read, leftSize);
index += leftSize;
return length;
}
if (available <= 0) {
// No more data in buffer, continue reading
readUnderlyingReader();
available = firstInvalidIndex - index;
if (available <= 0) {
// Cannot read any more, stop reading
if (read == 0) {
return -1;
}
else {
return read;
}
}
}
else {
// Copy all in-memory data, continue reading
System.arraycopy(buffer, index, charArray, read, available);
index += available;
read += available;
}
}
}
public String readLine() throws IOException {
if (reader == null) {
throw new IOException("Reader is null");
}
StringBundler sb = null;
while (true) {
if (index >= firstInvalidIndex) {
readUnderlyingReader();
}
if (index >= firstInvalidIndex) {
if ((sb != null) && (sb.index() > 0)) {
return sb.toString();
}
else {
return null;
}
}
boolean hasLineBreak = false;
char lineEndChar = 0;
int x = index;
int y = index;
while (y < firstInvalidIndex) {
lineEndChar = buffer[y];
if ((lineEndChar == CharPool.NEW_LINE) ||
(lineEndChar == CharPool.RETURN)) {
hasLineBreak = true;
break;
}
y++;
}
String line = new String(buffer, x, y - x);
index = y;
if (hasLineBreak) {
index++;
if (lineEndChar == CharPool.RETURN) {
if ((index < buffer.length) &&
(buffer[index] == CharPool.NEW_LINE)) {
index++;
}
}
if (sb == null) {
return line;
}
else {
sb.append(line);
return sb.toString();
}
}
if (sb == null) {
sb = new StringBundler();
}
sb.append(line);
}
}
public boolean ready() throws IOException {
if (reader == null) {
throw new IOException("Reader is null");
}
return (index < firstInvalidIndex) || reader.ready();
}
public void reset() throws IOException {
if (reader == null) {
throw new IOException("Reader is null");
}
if (markIndex < 0) {
throw new IOException("Resetting to invalid mark");
}
index = markIndex;
}
public long skip(long skip) throws IOException {
if (reader == null) {
throw new IOException("Reader is null");
}
if (skip <= 0) {
return 0;
}
long available = firstInvalidIndex - index;
if (available > 0) {
// Skip the data in buffer
if (available < skip) {
skip = available;
}
}
else {
// Skip the underlying reader
if (markIndex < 0) {
// No mark required, skip
skip = reader.skip(skip);
}
else {
// Mark required, save the skipped data
readUnderlyingReader();
available = firstInvalidIndex - index;
if (available > 0) {
// Skip the data in buffer
if (available < skip) {
skip = available;
}
}
}
}
index += skip;
return skip;
}
protected void readUnderlyingReader() throws IOException {
if (markIndex < 0) {
// No mark required, fill the buffer
index = firstInvalidIndex = 0;
int number = reader.read(buffer);
if (number > 0) {
firstInvalidIndex = number;
}
return;
}
// Mark required
if (index >= buffer.length) {
// Buffer is full, clean up or grow
if ((firstInvalidIndex - markIndex) > markLimit) {
// Passed mark limit, get rid of all cache data
markIndex = -1;
index = 0;
}
else if (markIndex > _MAX_MARK_WASTE_SIZE) {
// There are more than _MAX_MARK_WASTE_SIZE free space at the
// beginning of buffer, clean up by shuffling the buffer
int realDataSize = index - markIndex;
System.arraycopy(
buffer, markIndex, buffer, 0, realDataSize);
markIndex = 0;
index = realDataSize;
}
else {
// Grow the buffer because we cannot get rid of cache data and
// it is inefficient to shuffle the buffer
int newBufferSize = index << 1;
if ((newBufferSize - _MAX_MARK_WASTE_SIZE) > markLimit) {
// Make thew new buffer size larger than the mark limit
newBufferSize = markLimit + _MAX_MARK_WASTE_SIZE;
}
char[] newBuffer = new char[newBufferSize];
System.arraycopy(buffer, 0, newBuffer, 0, index);
buffer = newBuffer;
}
}
// Read underlying reader since the buffer has more space
firstInvalidIndex = index;
int number = reader.read(buffer, index, buffer.length - index);
if (number > 0) {
firstInvalidIndex += number;
}
}
protected char[] buffer;
protected int firstInvalidIndex;
protected int index;
protected int markIndex = -1;
protected int markLimit;
protected Reader reader;
private static int _DEFAULT_BUFFER_SIZE = 8192;
private static int _MAX_MARK_WASTE_SIZE = 4096;
}

View File

@ -0,0 +1,111 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.io.unsync;
import java.io.InputStream;
/**
* <p>
* See http://issues.liferay.com/browse/LPS-6648.
* </p>
*
* @author Shuyang Zhou
*/
public class UnsyncByteArrayInputStream extends InputStream {
public UnsyncByteArrayInputStream(byte[] buffer) {
this.buffer = buffer;
this.index = 0;
this.capacity = buffer.length;
}
public UnsyncByteArrayInputStream(byte[] buffer, int offset, int length) {
this.buffer = buffer;
this.index = offset;
this.capacity = Math.min(buffer.length, offset + length);
this.markIndex = offset;
}
public int available() {
return capacity - index;
}
public void mark(int readAheadLimit) {
markIndex = index;
}
public boolean markSupported() {
return true;
}
public int read() {
if (index < capacity) {
return buffer[index++] & 0xff;
}
else {
return -1;
}
}
public int read(byte[] byteArray) {
return read(byteArray, 0, byteArray.length);
}
public int read(byte[] byteArray, int offset, int length) {
if (length <= 0) {
return 0;
}
if (index >= capacity) {
return -1;
}
int read = length;
if ((index + read) > capacity) {
read = capacity - index;
}
System.arraycopy(buffer, index, byteArray, offset, read);
index += read;
return read;
}
public void reset() {
index = markIndex;
}
public long skip(long skip) {
if (skip < 0) {
return 0;
}
if ((skip + index) > capacity) {
skip = capacity - index;
}
index += skip;
return skip;
}
protected byte[] buffer;
protected int capacity;
protected int index;
protected int markIndex;
}

View File

@ -0,0 +1,125 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.io.unsync;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
/**
* <p>
* See http://issues.liferay.com/browse/LPS-6648.
* </p>
*
* @author Shuyang Zhou
*/
public class UnsyncByteArrayOutputStream extends OutputStream {
public UnsyncByteArrayOutputStream() {
this(32);
}
public UnsyncByteArrayOutputStream(int size) {
buffer = new byte[size];
}
public void reset() {
index = 0;
}
public int size() {
return index;
}
public byte[] toByteArray() {
byte[] newBuffer = new byte[index];
System.arraycopy(buffer, 0, newBuffer, 0, index);
return newBuffer;
}
public String toString() {
return new String(buffer, 0, index);
}
public String toString(String charsetName)
throws UnsupportedEncodingException {
return new String(buffer, 0, index, charsetName);
}
public byte[] unsafeGetByteArray() {
return buffer;
}
public ByteBuffer unsafeGetByteBuffer() {
return ByteBuffer.wrap(buffer, 0, index);
}
public void write(byte[] byteArray) {
write(byteArray, 0, byteArray.length);
}
public void write(byte[] byteArray, int offset, int length) {
if (length <= 0) {
return;
}
int newIndex = index + length;
if (newIndex > buffer.length) {
int newBufferSize = Math.max(buffer.length << 1, newIndex);
byte[] newBuffer = new byte[newBufferSize];
System.arraycopy(buffer, 0, newBuffer, 0, index);
buffer = newBuffer;
}
System.arraycopy(byteArray, offset, buffer, index, length);
index = newIndex;
}
public void write(int b) {
int newIndex = index + 1;
if (newIndex > buffer.length) {
int newBufferSize = Math.max(buffer.length << 1, newIndex);
byte[] newBuffer = new byte[newBufferSize];
System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
buffer = newBuffer;
}
buffer[index] = (byte)b;
index = newIndex;
}
public void writeTo(OutputStream outputStream) throws IOException {
outputStream.write(buffer, 0, index);
}
protected byte[] buffer;
protected int index;
}

View File

@ -0,0 +1,393 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.io.unsync;
import com.liferay.portal.kernel.util.StringPool;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Formatter;
import java.util.Locale;
/**
* <p>
* See http://issues.liferay.com/browse/LPS-6648.
* </p>
*
* @author Shuyang Zhou
*/
public class UnsyncPrintWriter extends PrintWriter {
public UnsyncPrintWriter(File file) throws IOException {
this(new FileWriter(file), false);
}
public UnsyncPrintWriter(File file, String csn)
throws FileNotFoundException, UnsupportedEncodingException {
this(new OutputStreamWriter(new FileOutputStream(file), csn), false);
}
public UnsyncPrintWriter(OutputStream outputStream) {
this(outputStream, false);
}
public UnsyncPrintWriter(OutputStream outputStream, boolean autoFlush) {
this(new OutputStreamWriter(outputStream), autoFlush);
}
public UnsyncPrintWriter(String fileName) throws IOException {
this(new FileWriter(fileName), false);
}
public UnsyncPrintWriter(String fileName, String csn)
throws FileNotFoundException, UnsupportedEncodingException {
this(
new OutputStreamWriter(new FileOutputStream(fileName), csn), false);
}
public UnsyncPrintWriter(Writer writer) {
this(writer, false);
}
public UnsyncPrintWriter(Writer writer, boolean autoFlush) {
super(writer);
_writer = writer;
_autoFlush = autoFlush;
}
public PrintWriter append(char c) {
write(c);
return this;
}
public PrintWriter append(CharSequence charSequence) {
if (charSequence == null) {
write(StringPool.NULL);
}
else {
write(charSequence.toString());
}
return this;
}
public PrintWriter append(CharSequence charSequence, int start, int end) {
if (charSequence == null) {
charSequence = StringPool.NULL;
}
write(charSequence.subSequence(start, end).toString());
return this;
}
public boolean checkError() {
if (_writer != null) {
flush();
}
return _hasError;
}
public void close() {
try {
if (_writer == null) {
return;
}
_writer.close();
_writer = null;
}
catch (IOException ioe) {
_hasError = true;
}
}
public void flush() {
if (_writer == null) {
_hasError = true;
}
else {
try {
_writer.flush();
}
catch (IOException ioe) {
_hasError = true;
}
}
}
public PrintWriter format(
Locale locale, String format, Object... arguments) {
if (_writer == null) {
_hasError = true;
}
else {
try {
if ((_formatter == null) || (_formatter.locale() != locale)) {
_formatter = new Formatter(this, locale);
}
_formatter.format(locale, format, arguments);
if (_autoFlush) {
_writer.flush();
}
}
catch (InterruptedIOException iioe) {
Thread currentThread = Thread.currentThread();
currentThread.interrupt();
}
catch (IOException ioe) {
_hasError = true;
}
}
return this;
}
public PrintWriter format(String format, Object... arguments) {
return format(Locale.getDefault(), format, arguments);
}
public void print(boolean b) {
if (b) {
write(StringPool.TRUE);
}
else {
write(StringPool.FALSE);
}
}
public void print(char c) {
write(c);
}
public void print(char[] charArray) {
write(charArray);
}
public void print(double d) {
write(String.valueOf(d));
}
public void print(float f) {
write(String.valueOf(f));
}
public void print(int i) {
write(String.valueOf(i));
}
public void print(long l) {
write(String.valueOf(l));
}
public void print(Object object) {
write(String.valueOf(object));
}
public void print(String string) {
if (string == null) {
string = StringPool.NULL;
}
write(string);
}
public PrintWriter printf(
Locale locale, String format, Object... arguments) {
return format(locale, format, arguments);
}
public PrintWriter printf(String format, Object... arguments) {
return format(format, arguments);
}
public void println() {
if (_writer == null) {
_hasError = true;
}
else {
try {
_writer.write(_LINE_SEPARATOR);
if (_autoFlush) {
_writer.flush();
}
}
catch (InterruptedIOException iioe) {
Thread currentThread = Thread.currentThread();
currentThread.interrupt();
}
catch (IOException ioe) {
_hasError = true;
}
}
}
public void println(boolean b) {
print(b);
println();
}
public void println(char c) {
print(c);
println();
}
public void println(char[] charArray) {
print(charArray);
println();
}
public void println(double d) {
print(d);
println();
}
public void println(float f) {
print(f);
println();
}
public void println(int i) {
print(i);
println();
}
public void println(long l) {
print(l);
println();
}
public void println(Object object) {
print(object);
println();
}
public void println(String string) {
print(string);
println();
}
public void write(char[] charArray) {
write(charArray, 0, charArray.length);
}
public void write(char[] charArray, int offset, int length) {
if (_writer == null) {
_hasError = true;
}
else {
try {
_writer.write(charArray, offset, length);
}
catch (InterruptedIOException iioe) {
Thread currentThread = Thread.currentThread();
currentThread.interrupt();
}
catch (IOException ioe) {
_hasError = true;
}
}
}
public void write(int c) {
if (_writer == null) {
_hasError = true;
}
else {
try {
_writer.write(c);
}
catch (InterruptedIOException iioe) {
Thread currentThread = Thread.currentThread();
currentThread.interrupt();
}
catch (IOException ioe) {
_hasError = true;
}
}
}
public void write(String string) {
if (_writer == null) {
_hasError = true;
}
else {
try {
_writer.write(string);
}
catch (InterruptedIOException iioe) {
Thread currentThread = Thread.currentThread();
currentThread.interrupt();
}
catch (IOException ioe) {
_hasError = true;
}
}
}
public void write(String string, int offset, int length) {
if (_writer == null) {
_hasError = true;
}
else {
try {
_writer.write(string, offset, length);
}
catch (InterruptedIOException iioe) {
Thread currentThread = Thread.currentThread();
currentThread.interrupt();
}
catch (IOException ioe) {
_hasError = true;
}
}
}
private static String _LINE_SEPARATOR = System.getProperty(
"line.separator");
private boolean _autoFlush;
private Formatter _formatter;
private boolean _hasError;
private Writer _writer;
}

View File

@ -0,0 +1,144 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.io.unsync;
import java.io.IOException;
import java.io.Reader;
import java.nio.CharBuffer;
/**
* <p>
* See http://issues.liferay.com/browse/LPS-6648.
* </p>
*
* @author Shuyang Zhou
*/
public class UnsyncStringReader extends Reader {
public UnsyncStringReader(String string) {
this.string = string;
stringLength = string.length();
}
public void close() {
string = null;
}
public void mark(int readAheadLimit) throws IOException {
if (string == null) {
throw new IOException("String is null");
}
markIndex = index;
}
public boolean markSupported() {
return true;
}
public int read() throws IOException {
if (string == null) {
throw new IOException("String is null");
}
if (index >= stringLength) {
return -1;
}
return string.charAt(index++);
}
public int read(char[] charArray) throws IOException {
return read(charArray, 0, charArray.length);
}
public int read(char[] charArray, int offset, int length)
throws IOException {
if (string == null) {
throw new IOException("String is null");
}
if (length <= 0) {
return 0;
}
if (index >= stringLength) {
return -1;
}
int read = length;
if ((index + read) > stringLength) {
read = stringLength - index;
}
string.getChars(index, index + read, charArray, offset);
index += read;
return read;
}
public int read(CharBuffer charBuffer) throws IOException {
int remaining = charBuffer.remaining();
char[] charArray = new char[remaining];
int read = read(charArray, 0, remaining);
if (read > 0) {
charBuffer.put(charArray, 0, read);
}
return read;
}
public boolean ready() throws IOException {
if (string == null) {
throw new IOException("String is null");
}
return true;
}
public void reset() throws IOException {
if (string == null) {
throw new IOException("String is null");
}
index = markIndex;
}
public long skip(long skip) {
if (index >= stringLength) {
return 0;
}
if ((skip + index) > stringLength) {
skip = stringLength - index;
}
index += skip;
return skip;
}
protected int index;
protected int stringLength;
protected int markIndex;
protected String string;
}

View File

@ -0,0 +1,166 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.io.unsync;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import java.io.Writer;
/**
* <p>
* See http://issues.liferay.com/browse/LPS-6648.
* </p>
*
* @author Shuyang Zhou
*/
public class UnsyncStringWriter extends Writer {
public UnsyncStringWriter() {
this(true);
}
public UnsyncStringWriter(boolean useStringBundler) {
if (useStringBundler) {
stringBundler = new StringBundler();
}
else {
stringBuilder = new StringBuilder();
}
}
public UnsyncStringWriter(boolean useStringBundler, int initialCapacity) {
if (useStringBundler) {
stringBundler = new StringBundler(initialCapacity);
}
else {
stringBuilder = new StringBuilder(initialCapacity);
}
}
public UnsyncStringWriter(int initialCapacity) {
this(true, initialCapacity);
}
public UnsyncStringWriter append(char c) {
write(c);
return this;
}
public UnsyncStringWriter append(CharSequence charSequence) {
if (charSequence == null) {
write(StringPool.NULL);
}
else {
write(charSequence.toString());
}
return this;
}
public UnsyncStringWriter append(
CharSequence charSequence, int start, int end) {
if (charSequence == null) {
charSequence = StringPool.NULL;
}
write(charSequence.subSequence(start, end).toString());
return this;
}
public void close() {
}
public void flush() {
}
public StringBuilder getStringBuilder() {
return stringBuilder;
}
public StringBundler getStringBundler() {
return stringBundler;
}
public void reset() {
if (stringBundler != null) {
stringBundler.setIndex(0);
}
else {
stringBuilder.setLength(0);
}
}
public String toString() {
if (stringBundler != null) {
return stringBundler.toString();
}
else {
return stringBuilder.toString();
}
}
public void write(char[] charArray, int offset, int length) {
if (length <= 0) {
return;
}
if (stringBundler != null) {
stringBundler.append(new String(charArray, offset, length));
}
else {
stringBuilder.append(charArray, offset, length);
}
}
public void write(char[] charArray) {
write(charArray, 0, charArray.length);
}
public void write(int c) {
if (stringBundler != null) {
stringBundler.append(String.valueOf((char)c));
}
else {
stringBuilder.append((char)c);
}
}
public void write(String string) {
if (stringBundler != null) {
stringBundler.append(string);
}
else {
stringBuilder.append(string);
}
}
public void write(String string, int offset, int length) {
if (stringBundler != null) {
stringBundler.append(string.substring(offset, offset + length));
}
else {
stringBuilder.append(string.substring(offset, offset + length));
}
}
protected StringBuilder stringBuilder;
protected StringBundler stringBundler;
}

View File

@ -0,0 +1,32 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.log;
import java.util.logging.Logger;
/**
* @author Brian Wing Shun Chan
*/
public class Jdk14LogFactoryImpl implements LogFactory {
public Log getLog(Class<?> c) {
return getLog(c.getName());
}
public Log getLog(String name) {
return new Jdk14LogImpl(Logger.getLogger(name));
}
}

View File

@ -0,0 +1,127 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.log;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Brian Wing Shun Chan
*/
public class Jdk14LogImpl implements Log {
public Jdk14LogImpl(Logger log) {
_log = log;
}
public void debug(Object msg) {
_log.log(Level.FINE, msg.toString());
}
public void debug(Throwable t) {
_log.log(Level.FINE, t.getMessage(), t);
}
public void debug(Object msg, Throwable t) {
_log.log(Level.FINE, msg.toString(), t);
}
public void error(Object msg) {
_log.log(Level.SEVERE, msg.toString());
}
public void error(Throwable t) {
_log.log(Level.SEVERE, t.getMessage(), t);
}
public void error(Object msg, Throwable t) {
_log.log(Level.SEVERE, msg.toString(), t);
}
public void fatal(Object msg) {
_log.log(Level.SEVERE, msg.toString());
}
public void fatal(Throwable t) {
_log.log(Level.SEVERE, t.getMessage(), t);
}
public void fatal(Object msg, Throwable t) {
_log.log(Level.SEVERE, msg.toString(), t);
}
public void info(Object msg) {
_log.log(Level.INFO, msg.toString());
}
public void info(Throwable t) {
_log.log(Level.INFO, t.getMessage(), t);
}
public void info(Object msg, Throwable t) {
_log.log(Level.INFO, msg.toString(), t);
}
public boolean isDebugEnabled() {
return _log.isLoggable(Level.FINE);
}
public boolean isErrorEnabled() {
return _log.isLoggable(Level.SEVERE);
}
public boolean isFatalEnabled() {
return _log.isLoggable(Level.SEVERE);
}
public boolean isInfoEnabled() {
return _log.isLoggable(Level.INFO);
}
public boolean isTraceEnabled() {
return _log.isLoggable(Level.FINEST);
}
public boolean isWarnEnabled() {
return _log.isLoggable(Level.WARNING);
}
public void trace(Object msg) {
_log.log(Level.FINEST, msg.toString());
}
public void trace(Throwable t) {
_log.log(Level.FINEST, t.getMessage(), t);
}
public void trace(Object msg, Throwable t) {
_log.log(Level.FINEST, msg.toString(), t);
}
public void warn(Object msg) {
_log.log(Level.WARNING, msg.toString());
}
public void warn(Throwable t) {
_log.log(Level.WARNING, t.getMessage(), t);
}
public void warn(Object msg, Throwable t) {
_log.log(Level.WARNING, msg.toString(), t);
}
private Logger _log;
}

View File

@ -0,0 +1,70 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.log;
/**
* @author Brian Wing Shun Chan
*/
public interface Log {
public void debug(Object msg);
public void debug(Throwable t);
public void debug(Object msg, Throwable t);
public void error(Object msg);
public void error(Throwable t);
public void error(Object msg, Throwable t);
public void fatal(Object msg);
public void fatal(Throwable t);
public void fatal(Object msg, Throwable t);
public void info(Object msg);
public void info(Throwable t);
public void info(Object msg, Throwable t);
public boolean isDebugEnabled();
public boolean isErrorEnabled();
public boolean isFatalEnabled();
public boolean isInfoEnabled();
public boolean isTraceEnabled();
public boolean isWarnEnabled();
public void trace(Object msg);
public void trace(Throwable t);
public void trace(Object msg, Throwable t);
public void warn(Object msg);
public void warn(Throwable t);
public void warn(Object msg, Throwable t);
}

View File

@ -0,0 +1,26 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.log;
/**
* @author Brian Wing Shun Chan
*/
public interface LogFactory {
public Log getLog(Class<?> c);
public Log getLog(String name);
}

View File

@ -0,0 +1,74 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.log;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* @author Brian Wing Shun Chan
* @author Shuyang Zhou
*/
public class LogFactoryUtil {
public static Log getLog(Class<?> c) {
return getLog(c.getName());
}
public static Log getLog(String name) {
// The following concurrent collection retrieve has the side effect of a
// memory fence read. This will invalidate all dirty cache data if there
// are any. If the LogWrapper swap happens before this, the new Log will
// be visible to the current Thread.
LogWrapper logWrapper = _logWrappers.get(name);
if (logWrapper == null) {
logWrapper = new LogWrapper(_logFactory.getLog(name));
LogWrapper previousLogWrapper = _logWrappers.putIfAbsent(
name, logWrapper);
if (previousLogWrapper != null) {
logWrapper = previousLogWrapper;
}
}
return logWrapper;
}
public static void setLogFactory(LogFactory logFactory) {
for (Map.Entry<String, LogWrapper> entry : _logWrappers.entrySet()) {
String name = entry.getKey();
LogWrapper logWrapper = entry.getValue();
logWrapper.setLog(logFactory.getLog(name));
}
// The following volatile write will flush out all cache data. All
// previously swapped LogWrappers will be visible for any reads after a
// memory fence read according to the happens-before rules.
_logFactory = logFactory;
}
private static volatile LogFactory _logFactory = new Jdk14LogFactoryImpl();
private static final ConcurrentMap<String, LogWrapper> _logWrappers =
new ConcurrentHashMap<String, LogWrapper>();
}

View File

@ -0,0 +1,222 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.log;
/**
* @author Brian Wing Shun Chan
*/
public class LogWrapper implements Log {
public LogWrapper(Log log) {
_log = log;
}
public void setLog(Log log) {
_log = log;
}
public void debug(Object msg) {
try {
_log.debug(msg);
}
catch (Exception e) {
printMsg(msg);
}
}
public void debug(Throwable t) {
try {
_log.debug(t);
}
catch (Exception e) {
printMsg(t.getMessage());
}
}
public void debug(Object msg, Throwable t) {
try {
_log.debug(msg, t);
}
catch (Exception e) {
printMsg(msg);
}
}
public void error(Object msg) {
try {
_log.error(msg);
}
catch (Exception e) {
printMsg(msg);
}
}
public void error(Throwable t) {
try {
_log.error(t);
}
catch (Exception e) {
printMsg(t.getMessage());
}
}
public void error(Object msg, Throwable t) {
try {
_log.error(msg, t);
}
catch (Exception e) {
printMsg(msg);
}
}
public void fatal(Object msg) {
try {
_log.fatal(msg);
}
catch (Exception e) {
printMsg(msg);
}
}
public void fatal(Throwable t) {
try {
_log.fatal(t);
}
catch (Exception e) {
printMsg(t.getMessage());
}
}
public void fatal(Object msg, Throwable t) {
try {
_log.fatal(msg, t);
}
catch (Exception e) {
printMsg(msg);
}
}
public void info(Object msg) {
try {
_log.info(msg);
}
catch (Exception e) {
printMsg(msg);
}
}
public void info(Throwable t) {
try {
_log.info(t);
}
catch (Exception e) {
printMsg(t.getMessage());
}
}
public void info(Object msg, Throwable t) {
try {
_log.info(msg, t);
}
catch (Exception e) {
printMsg(msg);
}
}
public boolean isDebugEnabled() {
return _log.isDebugEnabled();
}
public boolean isErrorEnabled() {
return _log.isErrorEnabled();
}
public boolean isFatalEnabled() {
return _log.isFatalEnabled();
}
public boolean isInfoEnabled() {
return _log.isInfoEnabled();
}
public boolean isTraceEnabled() {
return _log.isTraceEnabled();
}
public boolean isWarnEnabled() {
return _log.isWarnEnabled();
}
public void trace(Object msg) {
try {
_log.trace(msg);
}
catch (Exception e) {
printMsg(msg);
}
}
public void trace(Throwable t) {
try {
_log.trace(t);
}
catch (Exception e) {
printMsg(t.getMessage());
}
}
public void trace(Object msg, Throwable t) {
try {
_log.trace(msg, t);
}
catch (Exception e) {
printMsg(msg);
}
}
public void warn(Object msg) {
try {
_log.warn(msg);
}
catch (Exception e) {
printMsg(msg);
}
}
public void warn(Throwable t) {
try {
_log.warn(t);
}
catch (Exception e) {
printMsg(t.getMessage());
}
}
public void warn(Object msg, Throwable t) {
try {
_log.warn(msg, t);
}
catch (Exception e) {
printMsg(msg);
}
}
protected void printMsg(Object msg) {
System.err.println(msg);
}
private Log _log;
}

View File

@ -0,0 +1,216 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
/**
* @author Brian Wing Shun Chan
*/
public class CharPool {
public static final char AMPERSAND = '&';
public static final char APOSTROPHE = '\'';
public static final char AT = '@';
public static final char BACK_SLASH = '\\';
public static final char CLOSE_BRACKET = ']';
public static final char CLOSE_CURLY_BRACE = '}';
public static final char CLOSE_PARENTHESIS = ')';
public static final char COLON = ':';
public static final char COMMA = ',';
public static final char DASH = '-';
public static final char EQUAL = '=';
public static final char GREATER_THAN = '>';
public static final char FORWARD_SLASH = '/';
public static final char LESS_THAN = '<';
public static final char LOWER_CASE_A = 'a';
public static final char LOWER_CASE_B = 'b';
public static final char LOWER_CASE_C = 'c';
public static final char LOWER_CASE_D = 'd';
public static final char LOWER_CASE_E = 'e';
public static final char LOWER_CASE_F = 'f';
public static final char LOWER_CASE_G = 'g';
public static final char LOWER_CASE_H = 'h';
public static final char LOWER_CASE_I = 'i';
public static final char LOWER_CASE_J = 'j';
public static final char LOWER_CASE_K = 'k';
public static final char LOWER_CASE_L = 'l';
public static final char LOWER_CASE_M = 'm';
public static final char LOWER_CASE_N = 'n';
public static final char LOWER_CASE_O = 'o';
public static final char LOWER_CASE_P = 'p';
public static final char LOWER_CASE_Q = 'q';
public static final char LOWER_CASE_R = 'r';
public static final char LOWER_CASE_S = 's';
public static final char LOWER_CASE_T = 't';
public static final char LOWER_CASE_U = 'u';
public static final char LOWER_CASE_V = 'v';
public static final char LOWER_CASE_W = 'w';
public static final char LOWER_CASE_X = 'x';
public static final char LOWER_CASE_Y = 'y';
public static final char LOWER_CASE_Z = 'z';
public static final char MINUS = '-';
public static final char NEW_LINE = '\n';
public static final char NUMBER_0 = '0';
public static final char NUMBER_1 = '1';
public static final char NUMBER_2 = '2';
public static final char NUMBER_3 = '3';
public static final char NUMBER_4 = '4';
public static final char NUMBER_5 = '5';
public static final char NUMBER_6 = '6';
public static final char NUMBER_7 = '7';
public static final char NUMBER_8 = '8';
public static final char NUMBER_9 = '9';
public static final char OPEN_BRACKET = '[';
public static final char OPEN_CURLY_BRACE = '{';
public static final char OPEN_PARENTHESIS = '(';
public static final char PERCENT = '%';
public static final char PERIOD = '.';
public static final char PIPE = '|';
public static final char PLUS = '+';
public static final char POUND = '#';
public static final char QUESTION = '?';
public static final char QUOTE = '\"';
public static final char RAQUO = '\u00bb'; // '<27>'
public static final char RETURN = '\r';
public static final char SEMICOLON = ';';
public static final char SLASH = FORWARD_SLASH;
public static final char SPACE = ' ';
public static final char STAR = '*';
public static final char TAB = '\t';
public static final char TILDE = '~';
public static final char UNDERLINE = '_';
public static final char UPPER_CASE_A = 'A';
public static final char UPPER_CASE_B = 'B';
public static final char UPPER_CASE_C = 'C';
public static final char UPPER_CASE_D = 'D';
public static final char UPPER_CASE_E = 'E';
public static final char UPPER_CASE_F = 'F';
public static final char UPPER_CASE_G = 'G';
public static final char UPPER_CASE_H = 'H';
public static final char UPPER_CASE_I = 'I';
public static final char UPPER_CASE_J = 'J';
public static final char UPPER_CASE_K = 'K';
public static final char UPPER_CASE_L = 'L';
public static final char UPPER_CASE_M = 'M';
public static final char UPPER_CASE_N = 'N';
public static final char UPPER_CASE_O = 'O';
public static final char UPPER_CASE_P = 'P';
public static final char UPPER_CASE_Q = 'Q';
public static final char UPPER_CASE_R = 'R';
public static final char UPPER_CASE_S = 'S';
public static final char UPPER_CASE_T = 'T';
public static final char UPPER_CASE_U = 'U';
public static final char UPPER_CASE_V = 'V';
public static final char UPPER_CASE_W = 'W';
public static final char UPPER_CASE_X = 'X';
public static final char UPPER_CASE_Y = 'Y';
public static final char UPPER_CASE_Z = 'Z';
}

View File

@ -0,0 +1,332 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
import com.liferay.portal.kernel.io.unsync.UnsyncBufferedReader;
import com.liferay.portal.kernel.io.unsync.UnsyncStringReader;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StreamTokenizer;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Brian Wing Shun Chan
* @author Sandeep Soni
*/
public class ClassUtil {
public static Set<String> getClasses(File file) throws IOException {
String fileName = file.getName();
if (fileName.endsWith(".java")) {
fileName = fileName.substring(0, fileName.length() - 5);
}
return getClasses(new FileReader(file), fileName);
}
public static Set<String> getClasses(Reader reader, String className)
throws IOException {
Set<String> classes = new HashSet<String>();
StreamTokenizer st = new StreamTokenizer(
new UnsyncBufferedReader(reader));
_setupParseTableForAnnotationProcessing(st);
while (st.nextToken() != StreamTokenizer.TT_EOF) {
if (st.ttype == StreamTokenizer.TT_WORD) {
if (st.sval.equals("class") || st.sval.equals("enum") ||
st.sval.equals("interface") ||
st.sval.equals("@interface")) {
break;
}
else if (st.sval.startsWith("@")) {
st.ordinaryChar(' ');
st.wordChars('=', '=');
String[] las = _processAnnotation(st.sval, st);
for (int i = 0; i < las.length; i++) {
classes.add(las[i]);
}
_setupParseTableForAnnotationProcessing(st);
}
}
}
_setupParseTable(st);
while (st.nextToken() != StreamTokenizer.TT_EOF) {
if (st.ttype == StreamTokenizer.TT_WORD) {
if (st.sval.indexOf('.') >= 0) {
classes.add(st.sval.substring(0, st.sval.indexOf('.')));
}
else {
classes.add(st.sval);
}
}
else if (st.ttype != StreamTokenizer.TT_NUMBER &&
st.ttype != StreamTokenizer.TT_EOL) {
if (Character.isUpperCase((char)st.ttype)) {
classes.add(String.valueOf((char)st.ttype));
}
}
}
classes.remove(className);
return classes;
}
public static String getParentPath(
ClassLoader classLoader, String className) {
if (_log.isDebugEnabled()) {
_log.debug("Class name " + className);
}
if (!className.endsWith(_CLASS_EXTENSION)) {
className += _CLASS_EXTENSION;
}
className = StringUtil.replace(
className, StringPool.PERIOD, StringPool.SLASH);
className = StringUtil.replace(className, "/class", _CLASS_EXTENSION);
URL url = classLoader.getResource(className);
String path = null;
try {
path = new URI(url.getPath()).getPath();
}
catch (URISyntaxException urise) {
path = url.getFile();
}
if (_log.isDebugEnabled()) {
_log.debug("Path " + path);
}
int pos = path.indexOf(className);
String parentPath = path.substring(0, pos);
if (parentPath.startsWith("jar:")) {
parentPath = parentPath.substring(4, parentPath.length());
}
if (parentPath.startsWith("file:/")) {
parentPath = parentPath.substring(6, parentPath.length());
}
if (_log.isDebugEnabled()) {
_log.debug("Parent path " + parentPath);
}
return parentPath;
}
public static boolean isSubclass(Class<?> a, Class<?> b) {
if (a == b) {
return true;
}
if (a == null || b == null) {
return false;
}
for (Class<?> x = a; x != null; x = x.getSuperclass()) {
if (x == b) {
return true;
}
if (b.isInterface()) {
Class<?>[] interfaces = x.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
if (isSubclass(interfaces[i], b)) {
return true;
}
}
}
}
return false;
}
public static boolean isSubclass(Class<?> a, String s) {
if (a == null || s == null) {
return false;
}
if (a.getName().equals(s)) {
return true;
}
for (Class<?> x = a; x != null; x = x.getSuperclass()) {
if (x.getName().equals(s)) {
return true;
}
Class<?>[] interfaces = x.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
if (isSubclass(interfaces[i], s)) {
return true;
}
}
}
return false;
}
private static String[] _processAnnotation(String s, StreamTokenizer st)
throws IOException {
s = s.trim();
List<String> tokens = new ArrayList<String>();
Matcher annotationNameMatcher = _ANNOTATION_NAME_REGEXP.matcher(s);
Matcher annotationParametersMatcher =
_ANNOTATION_PARAMETERS_REGEXP.matcher(s);
if (annotationNameMatcher.matches()) {
String annotationName = annotationNameMatcher.group();
tokens.add(annotationName.replace("@", ""));
}
else if (annotationParametersMatcher.matches()) {
if (!s.trim().endsWith(")")) {
while (st.nextToken() != StreamTokenizer.TT_EOF) {
if (st.ttype == StreamTokenizer.TT_WORD) {
s += st.sval;
if (s.trim().endsWith(")")) {
break;
}
}
}
}
annotationParametersMatcher =
_ANNOTATION_PARAMETERS_REGEXP.matcher(s);
if (annotationParametersMatcher.matches()) {
String annotationName =
annotationParametersMatcher.group(1);
String annotationParameters =
annotationParametersMatcher.group(2);
tokens.add(annotationName.replace("@", ""));
tokens = _processAnnotationParameters(
annotationParameters,tokens);
}
}
return tokens.toArray(new String[tokens.size()]);
}
private static List<String> _processAnnotationParameters(
String s, List<String> tokens)
throws IOException {
StreamTokenizer st = new StreamTokenizer(new UnsyncStringReader(s));
_setupParseTable(st);
while (st.nextToken() != StreamTokenizer.TT_EOF) {
if (st.ttype == StreamTokenizer.TT_WORD) {
if (st.sval.indexOf('.') >= 0) {
tokens.add(st.sval.substring(0, st.sval.indexOf('.')));
}
else {
tokens.add(st.sval);
}
}
else if ((st.ttype != StreamTokenizer.TT_NUMBER) &&
(st.ttype != StreamTokenizer.TT_EOL)) {
if (Character.isUpperCase((char)st.ttype)) {
tokens.add(String.valueOf((char)st.ttype));
}
}
}
return tokens;
}
private static void _setupParseTable(StreamTokenizer st) {
st.resetSyntax();
st.slashSlashComments(true);
st.slashStarComments(true);
st.wordChars('a', 'z');
st.wordChars('A', 'Z');
st.wordChars('.', '.');
st.wordChars('0', '9');
st.wordChars('_', '_');
st.lowerCaseMode(false);
st.eolIsSignificant(false);
st.quoteChar('"');
st.quoteChar('\'');
st.parseNumbers();
}
private static void _setupParseTableForAnnotationProcessing(
StreamTokenizer st) {
_setupParseTable(st);
st.wordChars('@', '@');
st.wordChars('(', '(');
st.wordChars(')', ')');
st.wordChars('{', '{');
st.wordChars('}', '}');
st.wordChars(',',',');
}
private static final Pattern _ANNOTATION_NAME_REGEXP =
Pattern.compile("@(\\w+)$");
private static final Pattern _ANNOTATION_PARAMETERS_REGEXP =
Pattern.compile("@(\\w+)\\({0,1}\\{{0,1}([^)}]+)\\}{0,1}\\){0,1}");
private static final String _CLASS_EXTENSION = ".class";
private static Log _log = LogFactoryUtil.getLog(ClassUtil.class);
}

View File

@ -0,0 +1,157 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.List;
import java.util.Properties;
/**
* @author Brian Wing Shun Chan
* @author Alexander Chow
*/
public interface File {
public void copyDirectory(String sourceDirName, String destinationDirName);
public void copyDirectory(java.io.File source, java.io.File destination);
public void copyFile(String source, String destination);
public void copyFile(String source, String destination, boolean lazy);
public void copyFile(java.io.File source, java.io.File destination);
public void copyFile(
java.io.File source, java.io.File destination, boolean lazy);
public java.io.File createTempFile();
public java.io.File createTempFile(String extension);
public String createTempFileName();
public String createTempFileName(String extension);
public String decodeSafeFileName(String fileName);
public boolean delete(String file);
public boolean delete(java.io.File file);
public void deltree(String directory);
public void deltree(java.io.File directory);
public String encodeSafeFileName(String fileName);
public boolean exists(String fileName);
public boolean exists(java.io.File file);
public String extractText(InputStream is, String fileName);
public String getAbsolutePath(java.io.File file);
public byte[] getBytes(java.io.File file) throws IOException;
public byte[] getBytes(InputStream is) throws IOException;
public byte[] getBytes(InputStream is, int bufferSize) throws IOException;
public String getExtension(String fileName);
public String getPath(String fullFileName);
public String getShortFileName(String fullFileName);
public boolean isAscii(java.io.File file) throws IOException;
public String[] listDirs(String fileName);
public String[] listDirs(java.io.File file);
public String[] listFiles(String fileName);
public String[] listFiles(java.io.File file);
public void mkdirs(String pathName);
public boolean move(String sourceFileName, String destinationFileName);
public boolean move(java.io.File source, java.io.File destination);
public String read(String fileName) throws IOException;
public String read(java.io.File file) throws IOException;
public String read(java.io.File file, boolean raw) throws IOException;
public String replaceSeparator(String fileName);
public java.io.File[] sortFiles(java.io.File[] files);
public String stripExtension(String fileName);
public List<String> toList(Reader reader);
public List<String> toList(String fileName);
public Properties toProperties(java.io.FileInputStream fis);
public Properties toProperties(String fileName);
public void write(String fileName, String s) throws IOException;
public void write(String fileName, String s, boolean lazy)
throws IOException;
public void write(String fileName, String s, boolean lazy, boolean append)
throws IOException;
public void write(String pathName, String fileName, String s)
throws IOException;
public void write(String pathName, String fileName, String s, boolean lazy)
throws IOException;
public void write(
String pathName, String fileName, String s, boolean lazy,
boolean append)
throws IOException;
public void write(java.io.File file, String s) throws IOException;
public void write(java.io.File file, String s, boolean lazy)
throws IOException;
public void write(java.io.File file, String s, boolean lazy, boolean append)
throws IOException;
public void write(String fileName, byte[] bytes) throws IOException;
public void write(java.io.File file, byte[] bytes) throws IOException;
public void write(java.io.File file, byte[] bytes, int offset, int length)
throws IOException;
public void write(String fileName, InputStream is) throws IOException;
public void write(java.io.File file, InputStream is) throws IOException;
}

View File

@ -0,0 +1,313 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.List;
import java.util.Properties;
/**
* @author Brian Wing Shun Chan
* @author Alexander Chow
*/
public class FileUtil {
public static void copyDirectory(
String sourceDirName, String destinationDirName) {
getFile().copyDirectory(sourceDirName, destinationDirName);
}
public static void copyDirectory(File source, File destination) {
getFile().copyDirectory(source, destination);
}
public static void copyFile(String source, String destination) {
getFile().copyFile(source, destination);
}
public static void copyFile(
String source, String destination, boolean lazy) {
getFile().copyFile(source, destination, lazy);
}
public static void copyFile(File source, File destination) {
getFile().copyFile(source, destination);
}
public static void copyFile(File source, File destination, boolean lazy) {
getFile().copyFile(source, destination, lazy);
}
public static File createTempFile() {
return getFile().createTempFile();
}
public static File createTempFile(String extension) {
return getFile().createTempFile(extension);
}
public static String createTempFileName() {
return getFile().createTempFileName();
}
public static String createTempFileName(String extension) {
return getFile().createTempFileName(extension);
}
public static String decodeSafeFileName(String fileName) {
return getFile().decodeSafeFileName(fileName);
}
public static boolean delete(String file) {
return getFile().delete(file);
}
public static boolean delete(File file) {
return getFile().delete(file);
}
public static void deltree(String directory) {
getFile().deltree(directory);
}
public static void deltree(File directory) {
getFile().deltree(directory);
}
public static String encodeSafeFileName(String fileName) {
return getFile().encodeSafeFileName(fileName);
}
public static boolean exists(String fileName) {
return getFile().exists(fileName);
}
public static boolean exists(File file) {
return getFile().exists(file);
}
/**
* Extract text from an input stream and file name.
*
* @param is input stream of file
* @param fileName full name or extension of file (e.g., "Test.doc",
* ".doc")
* @return Extracted text if it is a supported format or an empty string if
* it is an unsupported format
*/
public static String extractText(InputStream is, String fileName) {
return getFile().extractText(is, fileName);
}
public static String getAbsolutePath(File file) {
return getFile().getAbsolutePath(file);
}
public static byte[] getBytes(File file) throws IOException {
return getFile().getBytes(file);
}
public static byte[] getBytes(InputStream is) throws IOException {
return getFile().getBytes(is);
}
public static byte[] getBytes(InputStream is, int bufferSize)
throws IOException {
return getFile().getBytes(is);
}
public static String getExtension(String fileName) {
return getFile().getExtension(fileName);
}
public static com.liferay.portal.kernel.util.File getFile() {
return _file;
}
public static String getPath(String fullFileName) {
return getFile().getPath(fullFileName);
}
public static String getShortFileName(String fullFileName) {
return getFile().getShortFileName(fullFileName);
}
public static boolean isAscii(File file) throws IOException {
return getFile().isAscii(file);
}
public static String[] listDirs(String fileName) {
return getFile().listDirs(fileName);
}
public static String[] listDirs(File file) {
return getFile().listDirs(file);
}
public static String[] listFiles(String fileName) {
return getFile().listFiles(fileName);
}
public static String[] listFiles(File file) {
return getFile().listFiles(file);
}
public static void mkdirs(String pathName) {
getFile().mkdirs(pathName);
}
public static boolean move(
String sourceFileName, String destinationFileName) {
return getFile().move(sourceFileName, destinationFileName);
}
public static boolean move(File source, File destination) {
return getFile().move(source, destination);
}
public static String read(String fileName) throws IOException {
return getFile().read(fileName);
}
public static String read(File file) throws IOException {
return getFile().read(file);
}
public static String read(File file, boolean raw) throws IOException {
return getFile().read(file, raw);
}
public static String replaceSeparator(String fileName) {
return getFile().replaceSeparator(fileName);
}
public static File[] sortFiles(File[] files) {
return getFile().sortFiles(files);
}
public static String stripExtension(String fileName) {
return getFile().stripExtension(fileName);
}
public static List<String> toList(Reader reader) {
return getFile().toList(reader);
}
public static List<String> toList(String fileName) {
return getFile().toList(fileName);
}
public static Properties toProperties(FileInputStream fis) {
return getFile().toProperties(fis);
}
public static Properties toProperties(String fileName) {
return getFile().toProperties(fileName);
}
public static void write(String fileName, String s) throws IOException {
getFile().write(fileName, s);
}
public static void write(String fileName, String s, boolean lazy)
throws IOException {
getFile().write(fileName, s, lazy);
}
public static void write(
String fileName, String s, boolean lazy, boolean append)
throws IOException {
getFile().write(fileName, s, lazy, append);
}
public static void write(String pathName, String fileName, String s)
throws IOException {
getFile().write(pathName, fileName, s);
}
public static void write(
String pathName, String fileName, String s, boolean lazy)
throws IOException {
getFile().write(pathName, fileName, s, lazy);
}
public static void write(
String pathName, String fileName, String s, boolean lazy,
boolean append)
throws IOException {
getFile().write(pathName, fileName, s, lazy, append);
}
public static void write(File file, String s) throws IOException {
getFile().write(file, s);
}
public static void write(File file, String s, boolean lazy)
throws IOException {
getFile().write(file, s, lazy);
}
public static void write(File file, String s, boolean lazy, boolean append)
throws IOException {
getFile().write(file, s, lazy, append);
}
public static void write(String fileName, byte[] bytes) throws IOException {
getFile().write(fileName, bytes);
}
public static void write(File file, byte[] bytes) throws IOException {
getFile().write(file, bytes);
}
public static void write(File file, byte[] bytes, int offset, int length)
throws IOException {
getFile().write(file, bytes, offset, length);
}
public static void write(String fileName, InputStream is)
throws IOException {
getFile().write(fileName, is);
}
public static void write(File file, InputStream is) throws IOException {
getFile().write(file, is);
}
public void setFile(com.liferay.portal.kernel.util.File file) {
_file = file;
}
private static com.liferay.portal.kernel.util.File _file;
}

View File

@ -0,0 +1,875 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
import java.io.Serializable;
import java.text.DateFormat;
import java.util.Date;
/**
* @author Brian Wing Shun Chan
*/
public class GetterUtil {
public static String[] BOOLEANS = {"true", "t", "y", "on", "1"};
public static final boolean DEFAULT_BOOLEAN = false;
public static final boolean[] DEFAULT_BOOLEAN_VALUES = new boolean[0];
public static final byte DEFAULT_BYTE = 0;
public static final byte[] DEFAULT_BYTE_VALUES = new byte[0];
public static final Date[] DEFAULT_DATE_VALUES = new Date[0];
public static final double DEFAULT_DOUBLE = 0.0;
public static final double[] DEFAULT_DOUBLE_VALUES = new double[0];
public static final float DEFAULT_FLOAT = 0;
public static final float[] DEFAULT_FLOAT_VALUES = new float[0];
public static final int DEFAULT_INTEGER = 0;
public static final int[] DEFAULT_INTEGER_VALUES = new int[0];
public static final long DEFAULT_LONG = 0;
public static final long[] DEFAULT_LONG_VALUES = new long[0];
public static final short DEFAULT_SHORT = 0;
public static final short[] DEFAULT_SHORT_VALUES = new short[0];
public static final String DEFAULT_STRING = StringPool.BLANK;
public static boolean get(Serializable value, boolean defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof String) {
return get((String)value, defaultValue);
}
else if (value.getClass().isAssignableFrom(Boolean.class)) {
return (Boolean)value;
}
return defaultValue;
}
public static Date get(
Serializable value, DateFormat dateFormat, Date defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof String) {
return get((String)value, dateFormat, defaultValue);
}
else if (value.getClass().isAssignableFrom(Date.class)) {
return (Date)value;
}
return defaultValue;
}
public static double get(Serializable value, double defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof String) {
return get((String)value, defaultValue);
}
else if (value.getClass().isAssignableFrom(Double.class)) {
return (Double)value;
}
return defaultValue;
}
public static float get(Serializable value, float defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof String) {
return get((String)value, defaultValue);
}
else if (value.getClass().isAssignableFrom(Float.class)) {
return (Float)value;
}
return defaultValue;
}
public static int get(Serializable value, int defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof String) {
return get((String)value, defaultValue);
}
else if (value.getClass().isAssignableFrom(Integer.class)) {
return (Integer)value;
}
return defaultValue;
}
public static long get(Serializable value, long defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof String) {
return get((String)value, defaultValue);
}
else if (value.getClass().isAssignableFrom(Long.class)) {
return (Long)value;
}
return defaultValue;
}
public static short get(Serializable value, short defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof String) {
return get((String)value, defaultValue);
}
else if (value.getClass().isAssignableFrom(Short.class)) {
return (Short)value;
}
return defaultValue;
}
public static String get(Serializable value, String defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof String) {
return get((String)value, defaultValue);
}
return defaultValue;
}
public static boolean get(String value, boolean defaultValue) {
if (value == null) {
return defaultValue;
}
try {
value = value.trim();
if (value.equalsIgnoreCase(BOOLEANS[0]) ||
value.equalsIgnoreCase(BOOLEANS[1]) ||
value.equalsIgnoreCase(BOOLEANS[2]) ||
value.equalsIgnoreCase(BOOLEANS[3]) ||
value.equalsIgnoreCase(BOOLEANS[4])) {
return true;
}
else {
return false;
}
}
catch (Exception e) {
}
return defaultValue;
}
public static Date get(
String value, DateFormat dateFormat, Date defaultValue) {
if (value == null) {
return defaultValue;
}
try {
Date date = dateFormat.parse(value.trim());
if (date != null) {
return date;
}
}
catch (Exception e) {
}
return defaultValue;
}
public static double get(String value, double defaultValue) {
if (value != null) {
try {
return Double.parseDouble(_trim(value));
}
catch (Exception e) {
}
}
return defaultValue;
}
public static float get(String value, float defaultValue) {
if (value == null) {
return defaultValue;
}
try {
return Float.parseFloat(_trim(value));
}
catch (Exception e) {
}
return defaultValue;
}
public static int get(String value, int defaultValue) {
if (value == null) {
return defaultValue;
}
return _parseInt(_trim(value), defaultValue);
}
public static long get(String value, long defaultValue) {
if (value == null) {
return defaultValue;
}
return _parseLong(_trim(value), defaultValue);
}
public static short get(String value, short defaultValue) {
if (value == null) {
return defaultValue;
}
return _parseShort(_trim(value), defaultValue);
}
public static String get(String value, String defaultValue) {
if (value == null) {
return defaultValue;
}
return StringUtil.replace(
value.trim(), StringPool.RETURN_NEW_LINE, StringPool.NEW_LINE);
}
public static boolean getBoolean(Serializable value) {
return getBoolean(value, DEFAULT_BOOLEAN);
}
public static boolean getBoolean(Serializable value, boolean defaultValue) {
return get(value, defaultValue);
}
public static boolean getBoolean(String value) {
return getBoolean(value, DEFAULT_BOOLEAN);
}
public static boolean getBoolean(String value, boolean defaultValue) {
return get(value, defaultValue);
}
public static boolean[] getBooleanValues(Serializable value) {
return getBooleanValues(value, DEFAULT_BOOLEAN_VALUES);
}
public static boolean[] getBooleanValues(
Serializable value, boolean[] defaultValue) {
Class<?> classObject = value.getClass();
if (classObject.isArray()) {
Class<?> componentType = classObject.getComponentType();
if (componentType.isAssignableFrom(String.class)) {
return getBooleanValues((String[])value, defaultValue);
}
else if (componentType.isAssignableFrom(Boolean.class)) {
return (boolean[])value;
}
}
return defaultValue;
}
public static boolean[] getBooleanValues(String[] values) {
return getBooleanValues(values, DEFAULT_BOOLEAN_VALUES);
}
public static boolean[] getBooleanValues(
String[] values, boolean[] defaultValue) {
if (values == null) {
return defaultValue;
}
boolean[] booleanValues = new boolean[values.length];
for (int i = 0; i < values.length; i++) {
booleanValues[i] = getBoolean(values[i]);
}
return booleanValues;
}
public static Date getDate(Serializable value, DateFormat dateFormat) {
return getDate(value, dateFormat, new Date());
}
public static Date getDate(
Serializable value, DateFormat dateFormat, Date defaultValue) {
return get(value, dateFormat, defaultValue);
}
public static Date getDate(String value, DateFormat dateFormat) {
return getDate(value, dateFormat, new Date());
}
public static Date getDate(
String value, DateFormat dateFormat, Date defaultValue) {
return get(value, dateFormat, defaultValue);
}
public static Date[] getDateValues(
Serializable value, DateFormat dateFormat) {
return getDateValues(value, dateFormat, DEFAULT_DATE_VALUES);
}
public static Date[] getDateValues(
Serializable value, DateFormat dateFormat, Date[] defaultValue) {
Class<?> classObject = value.getClass();
if (classObject.isArray()) {
Class<?> componentType = classObject.getComponentType();
if (componentType.isAssignableFrom(String.class)) {
return getDateValues((String[])value, dateFormat, defaultValue);
}
else if (componentType.isAssignableFrom(Date.class)) {
return (Date[])value;
}
}
return defaultValue;
}
public static Date[] getDateValues(String[] values, DateFormat dateFormat) {
return getDateValues(values, dateFormat, DEFAULT_DATE_VALUES);
}
public static Date[] getDateValues(
String[] values, DateFormat dateFormat, Date[] defaultValue) {
if (values == null) {
return defaultValue;
}
Date[] dateValues = new Date[values.length];
for (int i = 0; i < values.length; i++) {
dateValues[i] = getDate(values[i], dateFormat);
}
return dateValues;
}
public static double getDouble(Serializable value) {
return getDouble(value, DEFAULT_DOUBLE);
}
public static double getDouble(Serializable value, double defaultValue) {
return get(value, defaultValue);
}
public static double getDouble(String value) {
return getDouble(value, DEFAULT_DOUBLE);
}
public static double getDouble(String value, double defaultValue) {
return get(value, defaultValue);
}
public static double[] getDoubleValues(Serializable value) {
return getDoubleValues(value, DEFAULT_DOUBLE_VALUES);
}
public static double[] getDoubleValues(
Serializable value, double[] defaultValue) {
Class<?> classObject = value.getClass();
if (classObject.isArray()) {
Class<?> componentType = classObject.getComponentType();
if (componentType.isAssignableFrom(String.class)) {
return getDoubleValues((String[])value, defaultValue);
}
else if (componentType.isAssignableFrom(Double.class)) {
return (double[])value;
}
}
return defaultValue;
}
public static double[] getDoubleValues(String[] values) {
return getDoubleValues(values, DEFAULT_DOUBLE_VALUES);
}
public static double[] getDoubleValues(
String[] values, double[] defaultValue) {
if (values == null) {
return defaultValue;
}
double[] doubleValues = new double[values.length];
for (int i = 0; i < values.length; i++) {
doubleValues[i] = getDouble(values[i]);
}
return doubleValues;
}
public static float getFloat(Serializable value) {
return getFloat(value, DEFAULT_FLOAT);
}
public static float getFloat(Serializable value, float defaultValue) {
return get(value, defaultValue);
}
public static float getFloat(String value) {
return getFloat(value, DEFAULT_FLOAT);
}
public static float getFloat(String value, float defaultValue) {
return get(value, defaultValue);
}
public static float[] getFloatValues(Serializable value) {
return getFloatValues(value, DEFAULT_FLOAT_VALUES);
}
public static float[] getFloatValues(
Serializable value, float[] defaultValue) {
Class<?> classObject = value.getClass();
if (classObject.isArray()) {
Class<?> componentType = classObject.getComponentType();
if (componentType.isAssignableFrom(String.class)) {
return getFloatValues((String[])value, defaultValue);
}
else if (componentType.isAssignableFrom(Float.class)) {
return (float[])value;
}
}
return defaultValue;
}
public static float[] getFloatValues(String[] values) {
return getFloatValues(values, DEFAULT_FLOAT_VALUES);
}
public static float[] getFloatValues(
String[] values, float[] defaultValue) {
if (values == null) {
return defaultValue;
}
float[] floatValues = new float[values.length];
for (int i = 0; i < values.length; i++) {
floatValues[i] = getFloat(values[i]);
}
return floatValues;
}
public static int getInteger(Serializable value) {
return getInteger(value, DEFAULT_INTEGER);
}
public static int getInteger(Serializable value, int defaultValue) {
return get(value, defaultValue);
}
public static int getInteger(String value) {
return getInteger(value, DEFAULT_INTEGER);
}
public static int getInteger(String value, int defaultValue) {
return get(value, defaultValue);
}
public static int[] getIntegerValues(Serializable value) {
return getIntegerValues(value, DEFAULT_INTEGER_VALUES);
}
public static int[] getIntegerValues(
Serializable value, int[] defaultValue) {
Class<?> classObject = value.getClass();
if (classObject.isArray()) {
Class<?> componentType = classObject.getComponentType();
if (componentType.isAssignableFrom(String.class)) {
return getIntegerValues((String[])value, defaultValue);
}
else if (componentType.isAssignableFrom(Integer.class)) {
return (int[])value;
}
}
return defaultValue;
}
public static int[] getIntegerValues(String[] values) {
return getIntegerValues(values, DEFAULT_INTEGER_VALUES);
}
public static int[] getIntegerValues(String[] values, int[] defaultValue) {
if (values == null) {
return defaultValue;
}
int[] intValues = new int[values.length];
for (int i = 0; i < values.length; i++) {
intValues[i] = getInteger(values[i]);
}
return intValues;
}
public static long getLong(Serializable value) {
return getLong(value, DEFAULT_LONG);
}
public static long getLong(Serializable value, long defaultValue) {
return get(value, defaultValue);
}
public static long getLong(String value) {
return getLong(value, DEFAULT_LONG);
}
public static long getLong(String value, long defaultValue) {
return get(value, defaultValue);
}
public static long[] getLongValues(Serializable value) {
return getLongValues(value, DEFAULT_LONG_VALUES);
}
public static long[] getLongValues(
Serializable value, long[] defaultValue) {
Class<?> classObject = value.getClass();
if (classObject.isArray()) {
Class<?> componentType = classObject.getComponentType();
if (componentType.isAssignableFrom(String.class)) {
return getLongValues((String[])value, defaultValue);
}
else if (componentType.isAssignableFrom(Long.class)) {
return (long[])value;
}
}
return defaultValue;
}
public static long[] getLongValues(String[] values) {
return getLongValues(values, DEFAULT_LONG_VALUES);
}
public static long[] getLongValues(String[] values, long[] defaultValue) {
if (values == null) {
return defaultValue;
}
long[] longValues = new long[values.length];
for (int i = 0; i < values.length; i++) {
longValues[i] = getLong(values[i]);
}
return longValues;
}
public static short getShort(Serializable value) {
return getShort(value, DEFAULT_SHORT);
}
public static short getShort(Serializable value, short defaultValue) {
return get(value, defaultValue);
}
public static short getShort(String value) {
return getShort(value, DEFAULT_SHORT);
}
public static short getShort(String value, short defaultValue) {
return get(value, defaultValue);
}
public static short[] getShortValues(Serializable value) {
return getShortValues(value, DEFAULT_SHORT_VALUES);
}
public static short[] getShortValues(
Serializable value, short[] defaultValue) {
Class<?> classObject = value.getClass();
if (classObject.isArray()) {
Class<?> componentType = classObject.getComponentType();
if (componentType.isAssignableFrom(String.class)) {
return getShortValues((String[])value, defaultValue);
}
else if (componentType.isAssignableFrom(Short.class)) {
return (short[])value;
}
}
return defaultValue;
}
public static short[] getShortValues(String[] values) {
return getShortValues(values, DEFAULT_SHORT_VALUES);
}
public static short[] getShortValues(
String[] values, short[] defaultValue) {
if (values == null) {
return defaultValue;
}
short[] shortValues = new short[values.length];
for (int i = 0; i < values.length; i++) {
shortValues[i] = getShort(values[i]);
}
return shortValues;
}
public static String getString(Serializable value) {
return getString(value, DEFAULT_STRING);
}
public static String getString(Serializable value, String defaultValue) {
return get(value, defaultValue);
}
public static String getString(String value) {
return getString(value, DEFAULT_STRING);
}
public static String getString(String value, String defaultValue) {
return get(value, defaultValue);
}
private static int _parseInt(String value, int defaultValue) {
int length = value.length();
if (length <= 0) {
return defaultValue;
}
int pos = 0;
int limit = -Integer.MAX_VALUE;
boolean negative = false;
char c = value.charAt(0);
if (c < CharPool.NUMBER_0) {
if (c == CharPool.MINUS) {
limit = Integer.MIN_VALUE;
negative = true;
}
else if (c != CharPool.PLUS) {
return defaultValue;
}
if (length == 1) {
return defaultValue;
}
pos++;
}
int smallLimit = limit / 10;
int result = 0;
while (pos < length) {
if (result < smallLimit) {
return defaultValue;
}
c = value.charAt(pos++);
if ((c < CharPool.NUMBER_0) || (c > CharPool.NUMBER_9)) {
return defaultValue;
}
int number = c - CharPool.NUMBER_0;
result *= 10;
if (result < (limit + number)) {
return defaultValue;
}
result -= number;
}
if (negative) {
return result;
}
else {
return -result;
}
}
private static long _parseLong(String value, long defaultValue) {
int length = value.length();
if (length <= 0) {
return defaultValue;
}
int pos = 0;
long limit = -Long.MAX_VALUE;
boolean negative = false;
char c = value.charAt(0);
if (c < CharPool.NUMBER_0) {
if (c == CharPool.MINUS) {
limit = Long.MIN_VALUE;
negative = true;
}
else if (c != CharPool.PLUS) {
return defaultValue;
}
if (length == 1) {
return defaultValue;
}
pos++;
}
long smallLimit = limit / 10;
long result = 0;
while (pos < length) {
if (result < smallLimit) {
return defaultValue;
}
c = value.charAt(pos++);
if ((c < CharPool.NUMBER_0) || (c > CharPool.NUMBER_9)) {
return defaultValue;
}
int number = c - CharPool.NUMBER_0;
result *= 10;
if (result < (limit + number)) {
return defaultValue;
}
result -= number;
}
if (negative) {
return result;
}
else {
return -result;
}
}
private static short _parseShort(String value, short defaultValue) {
int i = _parseInt(value, defaultValue);
if ((i < Short.MIN_VALUE) || (i > Short.MAX_VALUE)) {
return defaultValue;
}
return (short)i;
}
private static String _trim(String value) {
value = value.trim();
int length = value.length();
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
char c = value.charAt(i);
if ((Character.isDigit(c)) ||
((c == CharPool.DASH) && (i == 0)) ||
(c == CharPool.PERIOD) || (c == CharPool.UPPER_CASE_E) ||
(c == CharPool.LOWER_CASE_E)) {
sb.append(c);
}
}
return sb.toString();
}
}

View File

@ -0,0 +1,126 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
// import com.liferay.portal.kernel.log.Log;
// import com.liferay.portal.kernel.log.LogFactoryUtil;
// import com.liferay.portal.kernel.log.LogUtil;
/**
* @author Brian Wing Shun Chan
*/
public class JavaProps {
public static final double JAVA_CLASS_VERSION_JDK_4 = 48.0;
public static final double JAVA_CLASS_VERSION_JDK_5 = 49.0;
public static final double JAVA_CLASS_VERSION_JDK_6 = 50.0;
public static final double JAVA_CLASS_VERSION_JDK_7 = 51.0;
public static String getJavaClassPath() {
return _instance._javaClassPath;
}
public static double getJavaClassVersion() {
return _instance._javaClassVersion;
}
public static String getJavaRuntimeVersion() {
return _instance._javaRuntimeVersion;
}
public static double getJavaSpecificationVersion() {
return _instance._javaSpecificationVersion;
}
public static String getJavaVersion() {
return _instance._javaVersion;
}
public static String getJavaVmVersion() {
return _instance._javaVmVersion;
}
public static boolean isJDK4() {
if (JavaProps.getJavaClassVersion() >=
JavaProps.JAVA_CLASS_VERSION_JDK_4) {
return true;
}
else {
return false;
}
}
public static boolean isJDK5() {
if (JavaProps.getJavaClassVersion() >=
JavaProps.JAVA_CLASS_VERSION_JDK_5) {
return true;
}
else {
return false;
}
}
public static boolean isJDK6() {
if (JavaProps.getJavaClassVersion() >=
JavaProps.JAVA_CLASS_VERSION_JDK_6) {
return true;
}
else {
return false;
}
}
public static boolean isJDK7() {
if (JavaProps.getJavaClassVersion() >=
JavaProps.JAVA_CLASS_VERSION_JDK_7) {
return true;
}
else {
return false;
}
}
private JavaProps() {
_javaClassPath = System.getProperty("java.class.path");
_javaClassVersion = Double.parseDouble(System.getProperty(
"java.class.version"));
_javaRuntimeVersion = System.getProperty("java.runtime.version");
_javaSpecificationVersion = Double.parseDouble(System.getProperty(
"java.specification.version"));
_javaVersion = System.getProperty("java.version");
_javaVmVersion = System.getProperty("java.vm.version");
// LogUtil.debug(_log, System.getProperties());
}
// private static Log _log = LogFactoryUtil.getLog(JavaProps.class);
private static JavaProps _instance = new JavaProps();
private String _javaClassPath;
private double _javaClassVersion;
private String _javaRuntimeVersion;
private double _javaSpecificationVersion;
private String _javaVersion;
private String _javaVmVersion;
}

View File

@ -0,0 +1,77 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
import java.io.Serializable;
/**
* @author Brian Wing Shun Chan
*/
public class KeyValuePair implements Comparable<KeyValuePair>, Serializable {
public KeyValuePair() {
this(null, null);
}
public KeyValuePair(String key, String value) {
_key = key;
_value = value;
}
public String getKey() {
return _key;
}
public void setKey(String key) {
_key = key;
}
public String getValue() {
return _value;
}
public void setValue(String value) {
_value = value;
}
public int compareTo(KeyValuePair kvp) {
return _key.compareTo(kvp.getKey());
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
KeyValuePair kvp = (KeyValuePair)obj;
String key = kvp.getKey();
if (_key.equals(key)) {
return true;
}
else {
return false;
}
}
public int hashCode() {
return _key.hashCode();
}
private String _key;
private String _value;
}

View File

@ -0,0 +1,125 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
* @author Brian Wing Shun Chan
*/
public class ListWrapper<E> implements List<E> {
public ListWrapper(List<E> list) {
_list = list;
}
public boolean add(E o) {
return _list.add(o);
}
public void add(int index, E element) {
_list.add(index, element);
}
public boolean addAll(Collection<? extends E> c) {
return _list.addAll(c);
}
public boolean addAll(int index, Collection<? extends E> c) {
return _list.addAll(index, c);
}
public void clear() {
_list.clear();
}
public boolean contains(Object o) {
return _list.contains(o);
}
public boolean containsAll(Collection<?> c) {
return _list.containsAll(c);
}
public E get(int index) {
return _list.get(index);
}
public int indexOf(Object o) {
return _list.indexOf(o);
}
public boolean isEmpty() {
return _list.isEmpty();
}
public Iterator<E> iterator() {
return _list.iterator();
}
public int lastIndexOf(Object o) {
return _list.lastIndexOf(o);
}
public ListIterator<E> listIterator() {
return _list.listIterator();
}
public ListIterator<E> listIterator(int index) {
return _list.listIterator(index);
}
public boolean remove(Object o) {
return _list.remove(o);
}
public E remove(int index) {
return _list.remove(index);
}
public boolean removeAll(Collection<?> c) {
return _list.removeAll(c);
}
public boolean retainAll(Collection<?> c) {
return _list.retainAll(c);
}
public E set(int index, E element) {
return _list.set(index, element);
}
public int size() {
return _list.size();
}
public List<E> subList(int fromIndex, int toIndex) {
return _list.subList(fromIndex, toIndex);
}
public Object[] toArray() {
return _list.toArray();
}
public <T> T[] toArray(T[] a) {
return _list.toArray(a);
}
private List<E> _list;
}

View File

@ -0,0 +1,124 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* @author Michael C. Han
*/
public class MethodCache {
public static Method get(String className, String methodName)
throws ClassNotFoundException, NoSuchMethodException {
return get(null, null, className, methodName);
}
public static Method get(
String className, String methodName, Class<?>[] parameterTypes)
throws ClassNotFoundException, NoSuchMethodException {
return get(null, null, className, methodName, parameterTypes);
}
public static Method get(
Map<String, Class<?>> classesMap, Map<MethodKey, Method> methodsMap,
String className, String methodName)
throws ClassNotFoundException, NoSuchMethodException {
return get(className, methodName, new Class[0]);
}
public static Method get(
Map<String, Class<?>> classesMap, Map<MethodKey, Method> methodsMap,
String className, String methodName, Class<?>[] parameterTypes)
throws ClassNotFoundException, NoSuchMethodException {
MethodKey methodKey = new MethodKey(
className, methodName, parameterTypes);
return _instance._get(classesMap, methodsMap, methodKey);
}
public static Method get(MethodKey methodKey)
throws ClassNotFoundException, NoSuchMethodException {
return _instance._get(null, null, methodKey);
}
public static Method put(MethodKey methodKey, Method method) {
return _instance._put(methodKey, method);
}
private MethodCache() {
_classesMap = new HashMap<String, Class<?>>();
_methodsMap = new HashMap<MethodKey, Method>();
}
private Method _get(
Map<String, Class<?>> classesMap, Map<MethodKey, Method> methodsMap,
MethodKey methodKey)
throws ClassNotFoundException, NoSuchMethodException {
if (classesMap == null) {
classesMap = _classesMap;
}
if (methodsMap == null) {
methodsMap = _methodsMap;
}
Method method = methodsMap.get(methodKey);
if (method == null) {
String className = methodKey.getClassName();
String methodName = methodKey.getMethodName();
Class<?>[] parameterTypes = methodKey.getParameterTypes();
Class<?> classObj = classesMap.get(className);
if (classObj == null) {
Thread currentThread = Thread.currentThread();
ClassLoader contextClassLoader =
currentThread.getContextClassLoader();
classObj = contextClassLoader.loadClass(className);
classesMap.put(className, classObj);
}
method = classObj.getMethod(methodName, parameterTypes);
methodsMap.put(methodKey, method);
}
return method;
}
private Method _put(MethodKey methodKey, Method method) {
return _methodsMap.put(methodKey, method);
}
private static MethodCache _instance = new MethodCache();
private Map<String, Class<?>> _classesMap;
private Map<MethodKey, Method> _methodsMap;
}

View File

@ -0,0 +1,99 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* @author Shuyang Zhou
*/
public class MethodHandler implements Serializable {
public MethodHandler(Method method, Object... arguments) {
this(new MethodKey(method), arguments);
}
public MethodHandler(MethodKey methodKey, Object... arguments) {
_methodKey = methodKey;
_arguments = arguments;
}
public Object[] getArguments() {
Object[] arguments = new Object[_arguments.length];
System.arraycopy(_arguments, 0, arguments, 0, _arguments.length);
return arguments;
}
public Class<?>[] getArgumentsClasses() {
return _methodKey.getParameterTypes();
}
public String getClassName() {
return _methodKey.getClassName();
}
public MethodKey getMethodKey() {
return _methodKey;
}
public String getMethodName() {
return _methodKey.getMethodName();
}
public Object invoke(boolean newInstance) throws Exception {
Thread currentThread = Thread.currentThread();
ClassLoader contextClassLoader = currentThread.getContextClassLoader();
Object targetObject = null;
if (newInstance) {
Class<?> targetClass = contextClassLoader.loadClass(
getClassName());
targetObject = targetClass.newInstance();
}
return invoke(targetObject);
}
public Object invoke(Object target) throws Exception {
Method method = MethodCache.get(_methodKey);
return method.invoke(target, _arguments);
}
public String toString() {
StringBundler sb = new StringBundler(5);
sb.append("{arguments=");
sb.append(Arrays.toString(_arguments));
sb.append(", methodKey=");
sb.append(_methodKey);
sb.append("}");
return sb.toString();
}
private Object[] _arguments;
private MethodKey _methodKey;
}

View File

@ -0,0 +1,261 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Brian Wing Shun Chan
* @author Harry Mark
* @author Shuyang Zhou
* @deprecated
*/
public class MethodInvoker {
public static Object invoke(MethodWrapper methodWrapper)
throws ClassNotFoundException, IllegalAccessException,
InstantiationException, InvocationTargetException,
NoSuchFieldException, NoSuchMethodException {
return invoke(methodWrapper, true);
}
public static Object invoke(
MethodWrapper methodWrapper, boolean newInstance)
throws ClassNotFoundException, IllegalAccessException,
InstantiationException, InvocationTargetException,
NoSuchFieldException, NoSuchMethodException {
Object targetObject = null;
if (newInstance) {
Thread currentThread = Thread.currentThread();
ClassLoader contextClassLoader =
currentThread.getContextClassLoader();
targetObject = contextClassLoader.loadClass(
methodWrapper.getClassName()).newInstance();
}
Object[] methodAndArguments = _lookupMethodAndArguments(
methodWrapper, targetObject);
Object returnObject = null;
if (methodAndArguments[0] != null) {
Method method = (Method)methodAndArguments[0];
Object[] arguments = (Object[])methodAndArguments[1];
returnObject = method.invoke(targetObject, arguments);
}
return returnObject;
}
public static Object invoke(
MethodWrapper methodWrapper, Object targetObject)
throws ClassNotFoundException, IllegalAccessException,
InvocationTargetException, NoSuchFieldException,
NoSuchMethodException {
Object[] methodAndArguments = _lookupMethodAndArguments(
methodWrapper, targetObject);
Object returnObject = null;
if (methodAndArguments[0] != null) {
Method method = (Method)methodAndArguments[0];
Object[] arguments = (Object[])methodAndArguments[1];
returnObject = method.invoke(targetObject, arguments);
}
return returnObject;
}
private static Object[] _lookupMethodAndArguments(
MethodWrapper methodWrapper, Object targetObject)
throws ClassNotFoundException, IllegalAccessException,
InvocationTargetException, NoSuchFieldException,
NoSuchMethodException {
Object[] methodAndArguments = new Object[2];
Thread currentThread = Thread.currentThread();
ClassLoader contextClassLoader = currentThread.getContextClassLoader();
String className = methodWrapper.getClassName();
String methodName = methodWrapper.getMethodName();
Object[] arguments = methodWrapper.getArguments();
String[] argumentClassNames = methodWrapper.getArgumentClassNames();
List<Class<?>> parameterTypes = new ArrayList<Class<?>>();
for (int i = 0; i < arguments.length; i++) {
if (arguments[i] == null) {
_log.error(
"Cannot invoke " + className + " " + methodName +
" on position " + i + " because it is null");
}
Class<?> argClass = null;
if (argumentClassNames != null) {
argClass = _primitiveTypeMap.get(argumentClassNames[i]);
if (argClass == null) {
argClass = Class.forName(
argumentClassNames[i], true, contextClassLoader);
}
}
else {
argClass = arguments[i].getClass();
}
if (ClassUtil.isSubclass(argClass, PrimitiveWrapper.class)) {
parameterTypes.add(
(Class<?>)argClass.getField("TYPE").get(arguments[i]));
MethodKey methodKey = new MethodKey(
argClass.getName(), "getValue");
Method method = MethodCache.get(methodKey);
arguments[i] = method.invoke(arguments[i], (Object[])null);
}
else if (arguments[i] instanceof NullWrapper) {
NullWrapper nullWrapper = (NullWrapper)arguments[i];
String wrappedClassName = nullWrapper.getClassName();
if (wrappedClassName.startsWith(StringPool.OPEN_BRACKET) &&
wrappedClassName.endsWith(StringPool.SEMICOLON)) {
wrappedClassName = wrappedClassName.substring(
2, wrappedClassName.length() - 1);
Class<?> wrappedClass = contextClassLoader.loadClass(
wrappedClassName);
parameterTypes.add(
Array.newInstance(wrappedClass, 0).getClass());
}
else {
Class<?> wrappedClass = contextClassLoader.loadClass(
wrappedClassName);
parameterTypes.add(wrappedClass);
}
arguments[i] = null;
}
else {
parameterTypes.add(argClass);
}
}
MethodKey methodKey = null;
Method method = null;
try {
methodKey = new MethodKey(
methodWrapper.getClassName(), methodWrapper.getMethodName(),
parameterTypes.toArray(new Class[parameterTypes.size()]));
method = MethodCache.get(methodKey);
}
catch (NoSuchMethodException nsme) {
Class<?> classObject = null;
if (targetObject == null) {
classObject = contextClassLoader.loadClass(className);
}
else {
classObject = targetObject.getClass();
}
Method[] methods = classObject.getMethods();
for (int i = 0; i < methods.length; i++) {
Class<?>[] methodParameterTypes =
methods[i].getParameterTypes();
if (methods[i].getName().equals(methodName) &&
methodParameterTypes.length == parameterTypes.size()) {
boolean correctParams = true;
for (int j = 0; j < parameterTypes.size(); j++) {
Class<?> a = parameterTypes.get(j);
Class<?> b = methodParameterTypes[j];
if (!ClassUtil.isSubclass(a, b)) {
correctParams = false;
break;
}
}
if (correctParams) {
method = methods[i];
MethodCache.put(methodKey, method);
break;
}
}
}
if (method == null) {
throw nsme;
}
}
methodAndArguments[0] = method;
methodAndArguments[1] = arguments;
return methodAndArguments;
}
private static Log _log = LogFactoryUtil.getLog(MethodInvoker.class);
private static Map<String, Class<?>> _primitiveTypeMap =
new HashMap<String, Class<?>>();
static {
_primitiveTypeMap.put("char", char.class);
_primitiveTypeMap.put("boolean", boolean.class);
_primitiveTypeMap.put("byte", byte.class);
_primitiveTypeMap.put("double", double.class);
_primitiveTypeMap.put("float", float.class);
_primitiveTypeMap.put("int", int.class);
_primitiveTypeMap.put("long", long.class);
_primitiveTypeMap.put("short", short.class);
}
}

View File

@ -0,0 +1,118 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
import java.io.Serializable;
import java.lang.reflect.Method;
/**
* @author Brian Wing Shun Chan
* @author Shuyang Zhou
*/
public class MethodKey implements Serializable {
public MethodKey(Method method) {
this(
method.getDeclaringClass().getName(), method.getName(),
method.getParameterTypes());
}
public MethodKey(
String className, String methodName, Class<?>... parameterTypes) {
_className = className;
_methodName = methodName;
_parameterTypes = parameterTypes;
}
public MethodKey(
String className, String methodName, String[] parameterTypeNames)
throws ClassNotFoundException {
_className = className;
_methodName = methodName;
_parameterTypes = new Class[parameterTypeNames.length];
for (int i = 0; i < parameterTypeNames.length; i++) {
String parameterTypeName = parameterTypeNames[i];
_parameterTypes[i] = Class.forName(parameterTypeName);
}
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
MethodKey methodKey = (MethodKey)obj;
if (toString().equals(methodKey.toString())) {
return true;
}
else {
return false;
}
}
public String getClassName() {
return _className;
}
public String getMethodName() {
return _methodName;
}
public Class<?>[] getParameterTypes() {
return _parameterTypes;
}
public int hashCode() {
return toString().hashCode();
}
public String toString() {
return _toString();
}
private String _toString() {
if (_toString == null) {
StringBundler sb = new StringBundler();
sb.append(_className);
sb.append(_methodName);
if ((_parameterTypes != null) && (_parameterTypes.length > 0)) {
sb.append(StringPool.DASH);
for (Class<?> parameterType : _parameterTypes) {
sb.append(parameterType.getName());
}
}
_toString = sb.toString();
}
return _toString;
}
private String _className;
private String _methodName;
private Class<?>[] _parameterTypes;
private String _toString;
}

View File

@ -0,0 +1,109 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* @author Brian Wing Shun Chan
* @deprecated
*/
public class MethodWrapper implements Serializable {
public MethodWrapper(String className, String methodName) {
this(className, methodName, new Object[0]);
}
public MethodWrapper(String className, String methodName, Object argument) {
this(className, methodName, new Object[] {argument});
}
public MethodWrapper(
String className, String methodName, Object[] arguments) {
_className = className;
_methodName = methodName;
_arguments = arguments;
}
public MethodWrapper(Method method, Object[] arguments) {
this(method.getDeclaringClass().getName(), method.getName(), arguments);
_argumentClassNames = new String[arguments.length];
Class<?>[] parameterTypes = method.getParameterTypes();
for (int i = 0; i < parameterTypes.length; i++) {
_argumentClassNames[i] = parameterTypes[i].getName();
}
}
public String getClassName() {
return _className;
}
public String getMethodName() {
return _methodName;
}
/**
* @deprecated Use <code>getArguments</code>.
*/
public Object[] getArgs() {
return getArguments();
}
public String[] getArgumentClassNames() {
return _argumentClassNames;
}
public Object[] getArguments() {
Object[] arguments = new Object[_arguments.length];
System.arraycopy(_arguments, 0, arguments, 0, _arguments.length);
return arguments;
}
public String toString() {
StringBundler sb = new StringBundler(9);
sb.append("{className=");
sb.append(_className);
sb.append(", methodName=");
sb.append(_methodName);
if (_argumentClassNames != null) {
sb.append(", argumentClassNames=");
sb.append(Arrays.toString(_argumentClassNames));
}
sb.append(", arguments=");
sb.append(Arrays.toString(_arguments));
sb.append("}");
return sb.toString();
}
private String _className;
private String _methodName;
private String[] _argumentClassNames;
private Object[] _arguments;
}

View File

@ -0,0 +1,34 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
import java.io.Serializable;
/**
* @author Brian Wing Shun Chan
*/
public class NullWrapper implements Serializable {
public NullWrapper(String className) {
_className = className;
}
public String getClassName() {
return _className;
}
private String _className;
}

View File

@ -0,0 +1,229 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
import java.lang.reflect.InvocationTargetException;
/**
* @author Brian Wing Shun Chan
* @author Shuyang Zhou
*/
public class PortalClassInvoker {
public static Object invoke(
boolean newInstance, MethodKey methodKey, Object... arguments)
throws Exception {
Thread currentThread = Thread.currentThread();
ClassLoader contextClassLoader = currentThread.getContextClassLoader();
try {
currentThread.setContextClassLoader(
PortalClassLoaderUtil.getClassLoader());
MethodHandler methodHandler = new MethodHandler(
methodKey, arguments);
return methodHandler.invoke(newInstance);
}
catch (InvocationTargetException ite) {
throw (Exception)ite.getCause();
}
finally {
currentThread.setContextClassLoader(contextClassLoader);
}
}
public static Object invoke(
boolean newInstance, String className, String methodName,
String[] parameterTypeNames, Object... arguments)
throws Exception {
Thread currentThread = Thread.currentThread();
ClassLoader contextClassLoader = currentThread.getContextClassLoader();
try {
currentThread.setContextClassLoader(
PortalClassLoaderUtil.getClassLoader());
MethodKey methodKey = new MethodKey(
className, methodName, parameterTypeNames);
MethodHandler methodHandler = new MethodHandler(
methodKey, arguments);
return methodHandler.invoke(newInstance);
}
catch (InvocationTargetException ite) {
throw (Exception)ite.getCause();
}
finally {
currentThread.setContextClassLoader(contextClassLoader);
}
}
/**
* @deprecated
*/
public static Object invoke(String className, String methodName)
throws Exception {
return invoke(className, methodName, new Object[] {});
}
/**
* @deprecated
*/
public static Object invoke(String className, String methodName, Object arg)
throws Exception {
return invoke(className, methodName, new Object[] {arg});
}
/**
* @deprecated
*/
public static Object invoke(
String className, String methodName, Object arg1, Object arg2)
throws Exception {
return invoke(className, methodName, new Object[] {arg1, arg2});
}
/**
* @deprecated
*/
public static Object invoke(
String className, String methodName, Object arg1, Object arg2,
Object arg3)
throws Exception {
return invoke(className, methodName, new Object[] {arg1, arg2, arg3});
}
/**
* @deprecated
*/
public static Object invoke(
String className, String methodName, Object[] args)
throws Exception {
return invoke(className, methodName, args, true);
}
/**
* @deprecated
*/
public static Object invoke(
String className, String methodName, boolean newInstance)
throws Exception {
return invoke(className, methodName, new Object[] {}, newInstance);
}
/**
* @deprecated
*/
public static Object invoke(
String className, String methodName, Object arg,
boolean newInstance)
throws Exception {
return invoke(className, methodName, new Object[] {arg}, newInstance);
}
/**
* @deprecated
*/
public static Object invoke(
String className, String methodName, Object arg1, Object arg2,
boolean newInstance)
throws Exception {
return invoke(
className, methodName, new Object[] {arg1, arg2}, newInstance);
}
/**
* @deprecated
*/
public static Object invoke(
String className, String methodName, Object arg1, Object arg2,
Object arg3, boolean newInstance)
throws Exception {
return invoke(
className, methodName, new Object[] {arg1, arg2, arg3},
newInstance);
}
/**
* @deprecated
*/
public static Object invoke(
String className, String methodName, Object arg1, Object arg2,
Object arg3, Object arg4, boolean newInstance)
throws Exception {
return invoke(
className, methodName, new Object[] {arg1, arg2, arg3, arg4},
newInstance);
}
/**
* @deprecated
*/
public static Object invoke(
String className, String methodName, Object arg1, Object arg2,
Object arg3, Object arg4, Object arg5, boolean newInstance)
throws Exception {
return invoke(
className, methodName, new Object[] {arg1, arg2, arg3, arg4, arg5},
newInstance);
}
/**
* @deprecated
*/
public static Object invoke(
String className, String methodName, Object[] args,
boolean newInstance)
throws Exception {
Thread currentThread = Thread.currentThread();
ClassLoader contextClassLoader = currentThread.getContextClassLoader();
try {
currentThread.setContextClassLoader(
PortalClassLoaderUtil.getClassLoader());
MethodWrapper methodWrapper = new MethodWrapper(
className, methodName, args);
return MethodInvoker.invoke(methodWrapper, newInstance);
}
catch (InvocationTargetException ite) {
throw (Exception)ite.getCause();
}
finally {
currentThread.setContextClassLoader(contextClassLoader);
}
}
}

View File

@ -0,0 +1,40 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
import java.net.URL;
import java.net.URLClassLoader;
/**
* @author Brian Wing Shun Chan
*/
public class PortalClassLoaderUtil {
public static ClassLoader getClassLoader() {
return _classLoader;
}
public static void setClassLoader(ClassLoader contextClassLoader) {
if (ServerDetector.isJOnAS() && JavaProps.isJDK6()) {
_classLoader = new URLClassLoader(new URL[0], contextClassLoader);
}
else {
_classLoader = contextClassLoader;
}
}
private static ClassLoader _classLoader;
}

View File

@ -0,0 +1,23 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
import java.io.Serializable;
/**
* @author Brian Wing Shun Chan
*/
public class PrimitiveWrapper implements Serializable {
}

View File

@ -0,0 +1,141 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
/**
* @author Brian Wing Shun Chan
*/
public class Randomizer extends Random {
public static Randomizer getInstance() {
return _instance;
}
public Randomizer() {
super();
}
public Randomizer(long seed) {
super(seed);
}
public int[] nextInt(int n, int size) {
if (size > n) {
size = n;
}
Set<Integer> set = new LinkedHashSet<Integer>();
for (int i = 0; i < size; i++) {
while (true) {
Integer value = new Integer(nextInt(n));
if (!set.contains(value)) {
set.add(value);
break;
}
}
}
int[] array = new int[set.size()];
Iterator<Integer> itr = set.iterator();
for (int i = 0; i < array.length; i++) {
array[i] = itr.next().intValue();
}
return array;
}
public void randomize(char array[]) {
int length = array.length;
for (int i = 0; i < length - 1; i++) {
int x = nextInt(length);
char y = array[i];
array[i] = array[i + x];
array[i + x] = y;
length--;
}
}
public void randomize(int array[]) {
int length = array.length;
for (int i = 0; i < length - 1; i++) {
int x = nextInt(length);
int y = array[i];
array[i] = array[i + x];
array[i + x] = y;
length--;
}
}
public void randomize(List<Object> list) {
int size = list.size();
for (int i = 0; i <= size; i++) {
Object obj = list.get(i);
int j = nextInt(size);
list.set(i, list.get(i + j));
list.set(i + j, obj);
size--;
}
}
public void randomize(Object array[]) {
int length = array.length;
for (int i = 0; i < length - 1; i++) {
int x = nextInt(length);
Object y = array[i];
array[i] = array[i + x];
array[i + x] = y;
length--;
}
}
public String randomize(String s) {
if (s == null) {
return null;
}
char[] array = s.toCharArray();
randomize(array);
return new String(array);
}
private static Randomizer _instance = new Randomizer();
}

View File

@ -0,0 +1,256 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
/**
* @author Brian Wing Shun Chan
*/
public class ServerDetector {
public static final String GERONIMO_ID = "geronimo";
public static final String GLASSFISH_ID = "glassfish";
public static final String JBOSS_ID = "jboss";
public static final String JETTY_ID = "jetty";
public static final String JONAS_ID = "jonas";
public static final String OC4J_ID = "oc4j";
public static final String RESIN_ID = "resin";
public static final String TOMCAT_ID = "tomcat";
public static final String WEBLOGIC_ID = "weblogic";
public static final String WEBSPHERE_ID = "websphere";
public static String getServerId() {
return _instance._serverId;
}
public static boolean isGeronimo() {
return _instance._geronimo;
}
public static boolean isGlassfish() {
return _instance._glassfish;
}
public static boolean isJBoss() {
return _instance._jBoss;
}
public static boolean isJetty() {
return _instance._jetty;
}
public static boolean isJOnAS() {
return _instance._jonas;
}
public static boolean isOC4J() {
return _instance._oc4j;
}
public static boolean isResin() {
return _instance._resin;
}
public static boolean isSupportsComet() {
return _instance._supportsComet;
}
public static boolean isTomcat() {
return _instance._tomcat;
}
public static boolean isWebLogic() {
return _instance._webLogic;
}
public static boolean isWebSphere() {
return _instance._webSphere;
}
private ServerDetector() {
if (_isGeronimo()) {
_serverId = GERONIMO_ID;
_geronimo = true;
}
else if (_isGlassfish()) {
_serverId = GLASSFISH_ID;
_glassfish = true;
}
else if (_isJBoss()) {
_serverId = JBOSS_ID;
_jBoss = true;
}
else if (_isJOnAS()) {
_serverId = JONAS_ID;
_jonas = true;
}
else if (_isOC4J()) {
_serverId = OC4J_ID;
_oc4j = true;
}
else if (_isResin()) {
_serverId = RESIN_ID;
_resin = true;
}
else if (_isWebLogic()) {
_serverId = WEBLOGIC_ID;
_webLogic = true;
}
else if (_isWebSphere()) {
_serverId = WEBSPHERE_ID;
_webSphere = true;
}
if (_isJetty()) {
if (_serverId == null) {
_serverId = JETTY_ID;
_jetty = true;
}
}
else if (_isTomcat()) {
if (_serverId == null) {
_serverId = TOMCAT_ID;
_tomcat = true;
}
}
if (System.getProperty("external-properties") == null) {
if (_log.isInfoEnabled()) {
if (_serverId != null) {
_log.info("Detected server " + _serverId);
}
else {
_log.info("No server detected");
}
}
}
/*if (_serverId == null) {
throw new RuntimeException("Server is not supported");
}*/
}
private boolean _detect(String className) {
try {
ClassLoader systemClassLoader =
ClassLoader.getSystemClassLoader();
systemClassLoader.loadClass(className);
return true;
}
catch (ClassNotFoundException cnfe) {
Class<?> classObj = getClass();
if (classObj.getResource(className) != null) {
return true;
}
else {
return false;
}
}
}
private boolean _isGeronimo() {
return _detect(
"/org/apache/geronimo/system/main/Daemon.class");
}
private boolean _isGlassfish() {
String value = System.getProperty("com.sun.aas.instanceRoot");
if (value != null) {
return true;
}
else {
return false;
}
}
private boolean _isJBoss() {
return _detect("/org/jboss/Main.class");
}
private boolean _isJetty() {
return _detect("/org/mortbay/jetty/Server.class");
}
private boolean _isJOnAS() {
boolean jonas = _detect("/org/objectweb/jonas/server/Server.class");
if (!_jonas && (System.getProperty("jonas.root") != null)) {
jonas = true;
}
return jonas;
}
private boolean _isOC4J() {
return _detect("oracle.oc4j.util.ClassUtils");
}
private boolean _isResin() {
return _detect("/com/caucho/server/resin/Resin.class");
}
private boolean _isTomcat() {
boolean tomcat = _detect(
"/org/apache/catalina/startup/Bootstrap.class");
if (!tomcat) {
tomcat = _detect("/org/apache/catalina/startup/Embedded.class");
}
return tomcat;
}
private boolean _isWebLogic() {
return _detect("/weblogic/Server.class");
}
private boolean _isWebSphere() {
return _detect(
"/com/ibm/websphere/product/VersionInfo.class");
}
private static Log _log = LogFactoryUtil.getLog(ServerDetector.class);
private static ServerDetector _instance = new ServerDetector();
private String _serverId;
private boolean _geronimo;
private boolean _glassfish;
private boolean _jBoss;
private boolean _jetty;
private boolean _jonas;
private boolean _oc4j;
private boolean _resin;
private boolean _supportsComet;
private boolean _tomcat;
private boolean _webLogic;
private boolean _webSphere;
}

View File

@ -0,0 +1,53 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
import com.liferay.portal.kernel.io.unsync.UnsyncPrintWriter;
import com.liferay.portal.kernel.io.unsync.UnsyncStringWriter;
import java.io.PrintWriter;
/**
* @author Brian Wing Shun Chan
*/
public class StackTraceUtil {
public static String getStackTrace(Throwable t) {
String stackTrace = null;
PrintWriter printWriter = null;
try {
UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();
printWriter = new UnsyncPrintWriter(unsyncStringWriter);
t.printStackTrace(printWriter);
printWriter.flush();
stackTrace = unsyncStringWriter.toString();
}
finally {
if (printWriter != null) {
printWriter.flush();
printWriter.close();
}
}
return stackTrace;
}
}

View File

@ -0,0 +1,337 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Constructor;
/**
* <p>
* See http://issues.liferay.com/browse/LPS-6072.
* </p>
*
* @author Shuyang Zhou
* @author Brian Wing Shun Chan
*/
public class StringBundler {
public static final int UNSAFE_CREATE_THRESHOLD = GetterUtil.getInteger(
System.getProperty(
StringBundler.class.getName() + ".unsafe.create.threshold"));
public StringBundler() {
_array = new String[_DEFAULT_ARRAY_CAPACITY];
}
public StringBundler(int initialCapacity) {
if (initialCapacity <= 0) {
throw new IllegalArgumentException();
}
_array = new String[initialCapacity];
}
public StringBundler(String s) {
_array = new String[_DEFAULT_ARRAY_CAPACITY];
_array[0] = s;
_arrayIndex = 1;
}
public StringBundler(String[] stringArray) {
this(stringArray, 0);
}
public StringBundler(String[] stringArray, int extraSpace) {
_array = new String[stringArray.length + extraSpace];
for (int i = 0; i < stringArray.length; i++) {
String s = stringArray[i];
if ((s != null) && (s.length() > 0)) {
_array[_arrayIndex++] = s;
}
}
}
public StringBundler append(boolean b) {
if (b) {
return append(_TRUE);
}
else {
return append(_FALSE);
}
}
public StringBundler append(char c) {
return append(String.valueOf(c));
}
public StringBundler append(char[] charArray) {
if (charArray == null) {
return append("null");
}
else {
return append(new String(charArray));
}
}
public StringBundler append(double d) {
return append(Double.toString(d));
}
public StringBundler append(float f) {
return append(Float.toString(f));
}
public StringBundler append(int i) {
return append(Integer.toString(i));
}
public StringBundler append(long l) {
return append(Long.toString(l));
}
public StringBundler append(Object obj) {
return append(String.valueOf(obj));
}
public StringBundler append(String s) {
if (s == null) {
s = StringPool.NULL;
}
if (s.length() == 0) {
return this;
}
if (_arrayIndex >= _array.length) {
expandCapacity(_array.length * 2);
}
_array[_arrayIndex++] = s;
return this;
}
public StringBundler append(String[] stringArray) {
if ((stringArray == null) || (stringArray.length == 0)) {
return this;
}
if ((_array.length - _arrayIndex) < stringArray.length) {
expandCapacity((_array.length + stringArray.length) * 2);
}
for (int i = 0; i < stringArray.length; i++) {
String s = stringArray[i];
if ((s != null) && (s.length() > 0)) {
_array[_arrayIndex++] = s;
}
}
return this;
}
public StringBundler append(StringBundler sb) {
if ((sb == null) || (sb._arrayIndex == 0)) {
return this;
}
if ((_array.length - _arrayIndex) < sb._arrayIndex) {
expandCapacity((_array.length + sb._arrayIndex) * 2);
}
System.arraycopy(sb._array, 0, _array, _arrayIndex, sb._arrayIndex);
_arrayIndex += sb._arrayIndex;
return this;
}
public int capacity() {
return _array.length;
}
public int index() {
return _arrayIndex;
}
public int length() {
int length = 0;
for (int i = 0; i < _arrayIndex; i++) {
length += _array[i].length();
}
return length;
}
public void setIndex(int newIndex) {
if (newIndex < 0) {
throw new ArrayIndexOutOfBoundsException(newIndex);
}
if (newIndex > _array.length) {
String[] newArray = new String[newIndex];
System.arraycopy(_array, 0, newArray, 0, _arrayIndex);
_array = newArray;
}
if (_arrayIndex < newIndex) {
for (int i = _arrayIndex; i < newIndex; i++) {
_array[i] = StringPool.BLANK;
}
}
if (_arrayIndex > newIndex) {
for (int i = newIndex; i < _arrayIndex; i++) {
_array[i] = null;
}
}
_arrayIndex = newIndex;
}
public void setStringAt(String s, int index) {
if ((index < 0) || (index >= _arrayIndex)) {
throw new ArrayIndexOutOfBoundsException(index);
}
_array[index] = s;
}
public String stringAt(int index) {
if ((index < 0) || (index >= _arrayIndex)) {
throw new ArrayIndexOutOfBoundsException(index);
}
return _array[index];
}
public String toString() {
if (_arrayIndex == 0) {
return StringPool.BLANK;
}
if (_arrayIndex == 1) {
return _array[0];
}
if (_arrayIndex == 2) {
return _array[0].concat(_array[1]);
}
int length = 0;
for (int i = 0; i < _arrayIndex; i++) {
length += _array[i].length();
}
if ((_unsafeStringConstructor != null) &&
(length >= UNSAFE_CREATE_THRESHOLD)) {
return unsafeCreate(_array, _arrayIndex, length);
}
else if (_arrayIndex == 3) {
return _array[0].concat(_array[1]).concat(_array[2]);
}
else {
return safeCreate(_array, _arrayIndex, length);
}
}
public void writeTo(Writer writer) throws IOException {
for (int i = 0; i < _arrayIndex; i++) {
writer.write(_array[i]);
}
}
protected void expandCapacity(int newCapacity) {
String[] newArray = new String[newCapacity];
System.arraycopy(_array, 0, newArray, 0, _arrayIndex);
_array = newArray;
}
protected String safeCreate(String[] array, int index, int length) {
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < index; i++) {
sb.append(array[i]);
}
return sb.toString();
}
protected String unsafeCreate(String[] array, int index, int length) {
char[] charArray = new char[length];
int offset = 0;
for (int i = 0; i < index; i++) {
String s = array[i];
s.getChars(0, s.length(), charArray, offset);
offset += s.length();
}
try {
return _unsafeStringConstructor.newInstance(0, length, charArray);
}
catch (Exception e) {
throw new IllegalStateException(e);
}
}
private static final int _DEFAULT_ARRAY_CAPACITY = 16;
private static final String _FALSE = "false";
private static final String _TRUE = "true";
private static Log _log = LogFactoryUtil.getLog(StringBundler.class);
private static Constructor<String> _unsafeStringConstructor;
static {
if (UNSAFE_CREATE_THRESHOLD > 0) {
try {
_unsafeStringConstructor = String.class.getDeclaredConstructor(
int.class, int.class, char[].class);
_unsafeStringConstructor.setAccessible(true);
}
catch (Exception e) {
_log.error(e, e);
}
}
}
private String[] _array;
private int _arrayIndex;
}

View File

@ -0,0 +1,166 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
/**
* @author Brian Wing Shun Chan
*/
public class StringPool {
public static final String AMPERSAND = "&";
public static final String AMPERSAND_ENCODED = "&amp;";
public static final String APOSTROPHE = "'";
public static final String AT = "@";
public static final String BACK_SLASH = "\\";
public static final String BETWEEN = "BETWEEN";
public static final String BLANK = "";
public static final String CARET = "^";
public static final String CDATA_CLOSE = "]]>";
public static final String CDATA_OPEN = "<![CDATA[";
public static final String CLOSE_BRACKET = "]";
public static final String CLOSE_CURLY_BRACE = "}";
public static final String CLOSE_PARENTHESIS = ")";
public static final String COLON = ":";
public static final String COMMA = ",";
public static final String COMMA_AND_SPACE = ", ";
public static final String DASH = "-";
public static final String DOLLAR = "$";
public static final String DOLLAR_AND_OPEN_CURLY_BRACE = "${";
public static final String DOUBLE_APOSTROPHE = "''";
public static final String DOUBLE_CLOSE_BRACKET = "]]";
public static final String DOUBLE_CLOSE_CURLY_BRACE = "}}";
public static final String DOUBLE_OPEN_BRACKET = "[[";
public static final String DOUBLE_OPEN_CURLY_BRACE = "{{";
public static final String DOUBLE_PERIOD = "..";
public static final String DOUBLE_QUOTE = "\"\"";
public static final String DOUBLE_SLASH = "//";
public static final String DOUBLE_SPACE = " ";
public static final String EXCLAMATION = "!";
public static final String EQUAL = "=";
public static final String FALSE = "false";
public static final String FORWARD_SLASH = "/";
public static final String FOUR_SPACES = " ";
public static final String GRAVE_ACCENT = "`";
public static final String GREATER_THAN = ">";
public static final String GREATER_THAN_OR_EQUAL = ">=";
public static final String INVERTED_EXCLAMATION = "\u00A1";
public static final String INVERTED_QUESTION = "\u00BF";
public static final String IS_NOT_NULL = "IS NOT NULL";
public static final String IS_NULL = "IS NULL";
public static final String ISO_8859_1 = "ISO-8859-1";
public static final String LESS_THAN = "<";
public static final String LESS_THAN_OR_EQUAL = "<=";
public static final String LIKE = "LIKE";
public static final String MINUS = "-";
public static final String NBSP = "&nbsp;";
public static final String NEW_LINE = "\n";
public static final String NOT_EQUAL = "!=";
public static final String NOT_LIKE = "NOT LIKE";
public static final String NULL = "null";
public static final String OPEN_BRACKET = "[";
public static final String OPEN_CURLY_BRACE = "{";
public static final String OPEN_PARENTHESIS = "(";
public static final String PERCENT = "%";
public static final String PERIOD = ".";
public static final String PIPE = "|";
public static final String PLUS = "+";
public static final String POUND = "#";
public static final String QUESTION = "?";
public static final String QUOTE = "\"";
public static final String RETURN = "\r";
public static final String RETURN_NEW_LINE = "\r\n";
public static final String SEMICOLON = ";";
public static final String SLASH = FORWARD_SLASH;
public static final String SPACE = " ";
public static final String STAR = "*";
public static final String TAB = "\t";
public static final String TILDE = "~";
public static final String TRUE = "true";
public static final String UNDERLINE = "_";
public static final String UTC = "UTC";
public static final String UTF8 = "UTF-8";
}

View File

@ -0,0 +1,116 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* @author Brian Wing Shun Chan
*/
public abstract class TranslatedList<E, F> extends ListWrapper<E> {
public TranslatedList(List<E> newList, List<F> oldList) {
super(newList);
_oldList = oldList;
}
public boolean add(E o) {
_oldList.add(toOldObject(o));
return super.add(o);
}
public void add(int index, E element) {
_oldList.add(index, toOldObject(element));
super.add(index, element);
}
public boolean addAll(Collection<? extends E> c) {
for (E o : c) {
_oldList.add(toOldObject(o));
}
return super.addAll(c);
}
public boolean addAll(int index, Collection<? extends E> c) {
for (E o : c) {
_oldList.add(index++, toOldObject(o));
}
return super.addAll(c);
}
public boolean remove(Object o) {
_oldList.remove(toOldObject((E)o));
return super.remove(o);
}
public E remove(int index) {
_oldList.remove(index);
return super.remove(index);
}
public boolean removeAll(Collection<?> c) {
List<F> tempList = new ArrayList<F>();
for (Object o : c) {
tempList.add(toOldObject((E)o));
}
_oldList.removeAll(tempList);
return super.removeAll(c);
}
public boolean retainAll(Collection<?> c) {
List<F> tempList = new ArrayList<F>();
for (Object o : c) {
tempList.add(toOldObject((E)o));
}
_oldList.retainAll(tempList);
return super.retainAll(c);
}
public E set(int index, E element) {
_oldList.set(index, toOldObject(element));
return super.set(index, element);
}
public List<E> subList(int fromIndex, int toIndex) {
List<E> newList = super.subList(fromIndex, toIndex);
List<F> oldList = _oldList.subList(fromIndex, toIndex);
return newInstance(newList, oldList);
}
protected abstract TranslatedList<E, F> newInstance(
List<E> newList, List<F> oldList);
protected abstract F toOldObject(E o);
private List<F> _oldList;
}

View File

@ -0,0 +1,123 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
/**
* @author Brian Wing Shun Chan
*/
public class UnicodeFormatter {
public static String byteToHex(byte b) {
char[] array = {_HEX_DIGITS[(b >> 4) & 0x0f], _HEX_DIGITS[b & 0x0f]};
return new String(array);
}
public static String charToHex(char c) {
byte hi = (byte)(c >>> 8);
byte lo = (byte)(c & 0xff);
char[] array = {
_HEX_DIGITS[(hi >> 4) & 0x0f], _HEX_DIGITS[hi & 0x0f],
_HEX_DIGITS[(lo >> 4) & 0x0f], _HEX_DIGITS[lo & 0x0f]
};
return new String(array);
}
public static String parseString(String hexString) {
StringBuilder sb = new StringBuilder();
char[] array = hexString.toCharArray();
if ((array.length % 6) != 0) {
_log.error("String is not in hex format");
return hexString;
}
for (int i = 2; i < hexString.length(); i = i + 6) {
String s = hexString.substring(i, i + 4);
try {
char c = (char)Integer.parseInt(s, 16);
sb.append(c);
}
catch (Exception e) {
_log.error(e, e);
return hexString;
}
}
return sb.toString();
}
public static String toString(char[] array) {
StringBuilder sb = new StringBuilder(array.length * 6);
char[] hexes = new char[4];
for (int i = 0; i < array.length; i++) {
sb.append(_UNICODE_PREFIX);
sb.append(_charToHex(array[i], hexes));
}
return sb.toString();
}
public static String toString(String s) {
if (s == null) {
return null;
}
StringBuilder sb = new StringBuilder(s.length() * 6);
char[] hexes = new char[4];
for (int i = 0; i < s.length(); i++) {
sb.append(_UNICODE_PREFIX);
sb.append(_charToHex(s.charAt(i), hexes));
}
return sb.toString();
}
private static char[] _charToHex(char c, char[] hexes) {
byte hi = (byte)(c >>> 8);
byte lo = (byte)(c & 0xff);
hexes[0] = _HEX_DIGITS[(hi >> 4) & 0x0f];
hexes[1] = _HEX_DIGITS[hi & 0x0f];
hexes[2] = _HEX_DIGITS[(lo >> 4) & 0x0f];
hexes[3] = _HEX_DIGITS[lo & 0x0f];
return hexes;
}
private static final char[] _HEX_DIGITS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f'
};
private static final String _UNICODE_PREFIX = "\\u";
private static Log _log = LogFactoryUtil.getLog(UnicodeFormatter.class);
}

View File

@ -0,0 +1,656 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.util;
// import com.liferay.portal.kernel.log.Log;
// import com.liferay.portal.kernel.log.LogFactoryUtil;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Brian Wing Shun Chan
* @author Alysa Carver
*/
public class Validator {
public static boolean equals(boolean boolean1, boolean boolean2) {
if (boolean1 == boolean2) {
return true;
}
else {
return false;
}
}
public static boolean equals(byte byte1, byte byte2) {
if (byte1 == byte2) {
return true;
}
else {
return false;
}
}
public static boolean equals(char char1, char char2) {
if (char1 == char2) {
return true;
}
else {
return false;
}
}
public static boolean equals(double double1, double double2) {
if (Double.compare(double1, double2) == 0) {
return true;
}
else {
return false;
}
}
public static boolean equals(float float1, float float2) {
if (Float.compare(float1, float2) == 0) {
return true;
}
else {
return false;
}
}
public static boolean equals(int int1, int int2) {
if (int1 == int2) {
return true;
}
else {
return false;
}
}
public static boolean equals(long long1, long long2) {
if (long1 == long2) {
return true;
}
else {
return false;
}
}
public static boolean equals(Object obj1, Object obj2) {
if ((obj1 == null) && (obj2 == null)) {
return true;
}
else if ((obj1 == null) || (obj2 == null)) {
return false;
}
else {
return obj1.equals(obj2);
}
}
public static boolean equals(short short1, short short2) {
if (short1 == short2) {
return true;
}
else {
return false;
}
}
public static boolean isAddress(String address) {
if (isNull(address)) {
return false;
}
String[] tokens = address.split(StringPool.AT);
if (tokens.length != 2) {
return false;
}
for (String token : tokens) {
for (char c : token.toCharArray()) {
if (Character.isWhitespace(c)) {
return false;
}
}
}
return true;
}
public static boolean isAscii(char c) {
int i = c;
if ((i >= 32) && (i <= 126)) {
return true;
}
else {
return false;
}
}
/**
* Returns <code>true</code> if c is a letter between a-z and A-Z.
*
* @return <code>true</code> if c is a letter between a-z and A-Z
*/
public static boolean isChar(char c) {
int x = c;
if ((x >= _CHAR_BEGIN) && (x <= _CHAR_END)) {
return true;
}
return false;
}
/**
* Returns <code>true</code> if s is a string of letters that are between
* a-z and A-Z.
*
* @return <code>true</code> if s is a string of letters that are between
* a-z and A-Z
*/
public static boolean isChar(String s) {
if (isNull(s)) {
return false;
}
for (char c : s.toCharArray()) {
if (!isChar(c)) {
return false;
}
}
return true;
}
public static boolean isDate(int month, int day, int year) {
return isGregorianDate(month, day, year);
}
/**
* Returns <code>true</code> if c is a digit between 0 and 9.
*
* @return <code>true</code> if c is a digit between 0 and 9
*/
public static boolean isDigit(char c) {
int x = c;
if ((x >= _DIGIT_BEGIN) && (x <= _DIGIT_END)) {
return true;
}
return false;
}
/**
* Returns <code>true</code> if s is a string of letters that are between 0
* and 9.
*
* @return <code>true</code> if s is a string of letters that are between 0
* and 9
*/
public static boolean isDigit(String s) {
if (isNull(s)) {
return false;
}
for (char c : s.toCharArray()) {
if (!isDigit(c)) {
return false;
}
}
return true;
}
public static boolean isDomain(String domainName) {
// See RFC-1034 (section 3), RFC-1123 (section 2.1), and RFC-952
// (section B. Lexical grammar)
if (isNull(domainName)) {
return false;
}
if (domainName.length() > 255) {
return false;
}
String[] domainNameArray = StringUtil.split(
domainName, StringPool.PERIOD);
for (String domainNamePart : domainNameArray) {
char[] domainNamePartCharArray = domainNamePart.toCharArray();
for (int i = 0; i < domainNamePartCharArray.length; i++) {
char c = domainNamePartCharArray[i];
if ((i == 0) && (c == CharPool.DASH)) {
return false;
}
else if ((i == (domainNamePartCharArray.length - 1)) &&
(c == CharPool.DASH)) {
return false;
}
else if ((!isChar(c)) && (!isDigit(c)) &&
(c != CharPool.DASH)) {
return false;
}
}
}
return true;
}
public static boolean isEmailAddress(String emailAddress) {
Boolean valid = null;
try {
valid = (Boolean)PortalClassInvoker.invoke(
true, isValidMethodKey, emailAddress);
}
catch (Exception e) {
// if (_log.isWarnEnabled()) {
// _log.warn(e);
// }
}
if (valid == null) {
return false;
}
else {
return valid.booleanValue();
}
}
public static boolean isEmailAddressSpecialChar(char c) {
// LEP-1445
for (int i = 0; i < _EMAIL_ADDRESS_SPECIAL_CHAR.length; i++) {
if (c == _EMAIL_ADDRESS_SPECIAL_CHAR[i]) {
return true;
}
}
return false;
}
public static boolean isGregorianDate(int month, int day, int year) {
if ((month < 0) || (month > 11)) {
return false;
}
int[] months = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (month == 1) {
int febMax = 28;
if (((year % 4) == 0) && ((year % 100) != 0) ||
((year % 400) == 0)) {
febMax = 29;
}
if ((day < 1) || (day > febMax)) {
return false;
}
}
else if ((day < 1) || (day > months[month])) {
return false;
}
return true;
}
public static boolean isHex(String s) {
if (isNull(s)) {
return false;
}
return true;
}
public static boolean isHTML(String s) {
if (isNull(s)) {
return false;
}
if (((s.indexOf("<html>") != -1) || (s.indexOf("<HTML>") != -1)) &&
((s.indexOf("</html>") != -1) || (s.indexOf("</HTML>") != -1))) {
return true;
}
return false;
}
public static boolean isIPAddress(String ipAddress) {
Matcher matcher = _ipAddressPattern.matcher(ipAddress);
return matcher.matches();
}
public static boolean isJulianDate(int month, int day, int year) {
if ((month < 0) || (month > 11)) {
return false;
}
int[] months = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (month == 1) {
int febMax = 28;
if ((year % 4) == 0) {
febMax = 29;
}
if ((day < 1) || (day > febMax)) {
return false;
}
}
else if ((day < 1) || (day > months[month])) {
return false;
}
return true;
}
public static boolean isLUHN(String number) {
if (number == null) {
return false;
}
number = StringUtil.reverse(number);
int total = 0;
for (int i = 0; i < number.length(); i++) {
int x = 0;
if (((i + 1) % 2) == 0) {
x = Integer.parseInt(number.substring(i, i + 1)) * 2;
if (x >= 10) {
String s = String.valueOf(x);
x = Integer.parseInt(s.substring(0, 1)) +
Integer.parseInt(s.substring(1, 2));
}
}
else {
x = Integer.parseInt(number.substring(i, i + 1));
}
total = total + x;
}
if ((total % 10) == 0) {
return true;
}
else {
return false;
}
}
public static boolean isName(String name) {
if (isNull(name)) {
return false;
}
for (char c : name.trim().toCharArray()) {
if (((!isChar(c)) &&
(!Character.isWhitespace(c))) || (c == CharPool.COMMA)) {
return false;
}
}
return true;
}
public static boolean isNotNull(Long l) {
return !isNull(l);
}
public static boolean isNotNull(Object obj) {
return !isNull(obj);
}
public static boolean isNotNull(Object[] array) {
return !isNull(array);
}
public static boolean isNotNull(String s) {
return !isNull(s);
}
public static boolean isNull(Long l) {
if ((l == null) || (l.longValue() == 0)) {
return true;
}
else {
return false;
}
}
public static boolean isNull(Object obj) {
if (obj instanceof Long) {
return isNull((Long)obj);
}
else if (obj instanceof String) {
return isNull((String)obj);
}
else if (obj == null) {
return true;
}
else {
return false;
}
}
public static boolean isNull(Object[] array) {
if ((array == null) || (array.length == 0)) {
return true;
}
else {
return false;
}
}
public static boolean isNull(String s) {
if (s == null) {
return true;
}
int counter = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == CharPool.SPACE) {
continue;
}
else if (counter > 3) {
return false;
}
if (counter == 0) {
if (c != CharPool.LOWER_CASE_N) {
return false;
}
}
else if (counter == 1) {
if (c != CharPool.LOWER_CASE_U) {
return false;
}
}
else if ((counter == 2) || (counter == 3)) {
if (c != CharPool.LOWER_CASE_L) {
return false;
}
}
counter++;
}
if ((counter == 0) || (counter == 4)) {
return true;
}
return false;
}
public static boolean isNumber(String number) {
if (isNull(number)) {
return false;
}
for (char c : number.toCharArray()) {
if (!isDigit(c)) {
return false;
}
}
return true;
}
public static boolean isPassword(String password) {
if (isNull(password)) {
return false;
}
if (password.length() < 4) {
return false;
}
for (char c : password.toCharArray()) {
if (!isChar(c) && !isDigit(c)) {
return false;
}
}
return true;
}
public static boolean isPhoneNumber(String phoneNumber) {
return isNumber(StringUtil.extractDigits(phoneNumber));
}
public static boolean isUrl(String url) {
if (Validator.isNotNull(url)) {
try {
new URL(url);
return true;
}
catch (MalformedURLException murle) {
}
}
return false;
}
public static boolean isVariableName(String variableName) {
if (isNull(variableName)) {
return false;
}
Matcher matcher = _variableNamePattern.matcher(variableName);
if (matcher.matches()) {
return true;
}
else {
return false;
}
}
public static boolean isVariableTerm(String s) {
if (s.startsWith(_VARIABLE_TERM_BEGIN) &&
s.endsWith(_VARIABLE_TERM_END)) {
return true;
}
else {
return false;
}
}
public static boolean isWhitespace(char c) {
int i = c;
if ((i == 0) || Character.isWhitespace(c)) {
return true;
}
else {
return false;
}
}
public static boolean isXml(String s) {
if (s.startsWith(_XML_BEGIN) || s.startsWith(_XML_EMPTY)) {
return true;
}
else {
return false;
}
}
private static final int _CHAR_BEGIN = 65;
private static final int _CHAR_END = 122;
private static final int _DIGIT_BEGIN = 48;
private static final int _DIGIT_END = 57;
private static final char[] _EMAIL_ADDRESS_SPECIAL_CHAR = new char[] {
'.', '!', '#', '$', '%', '&', '\'', '*', '+', '-', '/', '=', '?', '^',
'_', '`', '{', '|', '}', '~'
};
private static final String _VARIABLE_TERM_BEGIN = "[$";
private static final String _VARIABLE_TERM_END = "$]";
private static final String _XML_BEGIN = "<?xml";
private static final String _XML_EMPTY = "<root />";
// private static Log _log = LogFactoryUtil.getLog(Validator.class);
private static Pattern _ipAddressPattern = Pattern.compile(
"\\b" +
"((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\." +
"((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\." +
"((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\." +
"((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])" +
"\\b");
private static MethodKey isValidMethodKey = new MethodKey(
"com.liferay.util.mail.InternetAddressUtil", "isValid", String.class);
private static Pattern _variableNamePattern = Pattern.compile(
"[_a-zA-Z]+[_a-zA-Z0-9]*");
}

View File

@ -0,0 +1,42 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.xml;
/**
* @author Brian Wing Shun Chan
*/
public interface Attribute extends Node {
public Object getData();
public Namespace getNamespace();
public String getNamespacePrefix();
public String getNamespaceURI();
public QName getQName();
public String getQualifiedName();
public String getValue();
public void setData(Object data);
public void setNamespace(Namespace namespace);
public void setValue(String value);
}

View File

@ -0,0 +1,78 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.xml;
import java.util.Iterator;
import java.util.List;
/**
* @author Brian Wing Shun Chan
*/
public interface Branch extends Node {
public void add(Comment comment);
public void add(Element element);
public void add(Node node);
public void add(ProcessingInstruction processingInstruction);
public Element addElement(QName qName);
public Element addElement(String name);
public Element addElement(String qualifiedName, String namespaceURI);
public void appendContent(Branch branch);
public void clearContent();
public List<Node> content();
public Element elementByID(String elementID);
public int indexOf(Node node);
public Node node(int index);
public int nodeCount();
public Iterator<Node> nodeIterator();
public void normalize();
public ProcessingInstruction processingInstruction(String target);
public List<ProcessingInstruction> processingInstructions();
public List<ProcessingInstruction> processingInstructions(String target);
public boolean remove(Comment comment);
public boolean remove(Element element);
public boolean remove(Node node);
public boolean remove(ProcessingInstruction processingInstruction);
public boolean removeProcessingInstruction(String target);
public void setContent(List<Node> content);
public void setProcessingInstructions(
List<ProcessingInstruction> processingInstructions);
}

View File

@ -0,0 +1,21 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.xml;
/**
* @author Brian Wing Shun Chan
*/
public interface CDATA extends Node {
}

View File

@ -0,0 +1,21 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.xml;
/**
* @author Brian Wing Shun Chan
*/
public interface Comment extends Node {
}

View File

@ -0,0 +1,43 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.xml;
import java.io.IOException;
/**
* @author Brian Wing Shun Chan
*/
public interface Document extends Branch {
public Document addComment(String comment);
public Document addDocType(String name, String publicId, String systemId);
public String formattedString() throws IOException;
public String formattedString(String indent) throws IOException;
public String formattedString(String indent, boolean expandEmptyElements)
throws IOException;
public Element getRootElement();
public String getXMLEncoding();
public void setRootElement(Element rootElement);
public void setXMLEncoding(String encoding);
}

View File

@ -0,0 +1,38 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.xml;
/**
* @author Brian Wing Shun Chan
*/
public class DocumentException extends Exception {
public DocumentException() {
super();
}
public DocumentException(String msg) {
super(msg);
}
public DocumentException(Throwable cause) {
super(cause);
}
public DocumentException(String msg, Throwable cause) {
super(msg, cause);
}
}

View File

@ -0,0 +1,161 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.xml;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* @author Brian Wing Shun Chan
*/
public interface Element extends Branch {
public void add(Attribute attribute);
public void add(CDATA cdata);
public void add(Entity entity);
public void add(Namespace namespace);
public void add(Text text);
public Element addAttribute(QName qName, String value);
public Element addAttribute(String name, String value);
public Element addCDATA(String cdata);
public Element addComment(String comment);
public Element addEntity(String name, String text);
public List<Namespace> additionalNamespaces();
public Element addNamespace(String prefix, String uri);
public Element addProcessingInstruction(
String target, Map<String, String> data);
public Element addProcessingInstruction(String target, String data);
public Element addText(String text);
public void appendAttributes(Element element);
public Attribute attribute(int index);
public Attribute attribute(QName qName);
public Attribute attribute(String name);
public int attributeCount();
public Iterator<Attribute> attributeIterator();
public List<Attribute> attributes();
public String attributeValue(QName qName);
public String attributeValue(QName qName, String defaultValue);
public String attributeValue(String name);
public String attributeValue(String name, String defaultValue);
public Element createCopy();
public Element createCopy(QName qName);
public Element createCopy(String name);
public List<Namespace> declaredNamespaces();
public Element element(QName qName);
public Element element(String name);
public Iterator<Element> elementIterator();
public Iterator<Element> elementIterator(QName qName);
public Iterator<Element> elementIterator(String name);
public List<Element> elements();
public List<Element> elements(QName qName);
public List<Element> elements(String name);
public String elementText(QName qName);
public String elementText(String name);
public String elementTextTrim(QName qName);
public String elementTextTrim(String name);
public Object getData();
public Namespace getNamespace();
public Namespace getNamespaceForPrefix(String prefix);
public Namespace getNamespaceForURI(String uri);
public String getNamespacePrefix();
public List<Namespace> getNamespacesForURI(String uri);
public String getNamespaceURI();
public QName getQName();
public QName getQName(String qualifiedName);
public String getQualifiedName();
public String getStringValue();
public String getText();
public String getTextTrim();
public Node getXPathResult(int index);
public boolean hasMixedContent();
public boolean isRootElement();
public boolean isTextOnly();
public boolean remove(Attribute attribute);
public boolean remove(CDATA cdata);
public boolean remove(Entity entity);
public boolean remove(Namespace namespace);
public boolean remove(Text text);
public void setAttributes(List<Attribute> attributes);
public void setData(Object data);
public void setQName(QName qName);
}

View File

@ -0,0 +1,21 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.xml;
/**
* @author Brian Wing Shun Chan
*/
public interface Entity extends Node {
}

View File

@ -0,0 +1,30 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.xml;
/**
* @author Brian Wing Shun Chan
*/
public interface Namespace extends Node {
public short getNodeType();
public String getPrefix();
public String getURI();
public String getXPathNameStep();
}

View File

@ -0,0 +1,83 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.xml;
import java.io.IOException;
import java.io.Serializable;
import java.io.Writer;
import java.util.List;
/**
* @author Brian Wing Shun Chan
*/
public interface Node extends Serializable {
public String asXML();
public Node asXPathResult(Element parent);
public Node detach();
public Document getDocument();
public String getName();
public Element getParent();
public String getPath();
public String getPath(Element context);
public String getStringValue();
public String getText();
public String getUniquePath();
public String getUniquePath(Element context);
public boolean hasContent();
public boolean isReadOnly();
public boolean matches(String xpathExpression);
public Number numberValueOf(String xpathExpression);
public List<Node> selectNodes(String xpathExpression);
public List<Node> selectNodes(
String xpathExpression, String comparisonXPathExpression);
public List<Node> selectNodes(
String xpathExpression, String comparisonXPathExpression,
boolean removeDuplicates);
public Object selectObject(String xpathExpression);
public Node selectSingleNode(String xpathExpression);
public void setName(String name);
public void setText(String text);
public boolean supportsParent();
public String valueOf(String xpathExpression);
public void write(Writer writer) throws IOException;
}

View File

@ -0,0 +1,40 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.xml;
import java.util.Map;
/**
* @author Brian Wing Shun Chan
*/
public interface ProcessingInstruction extends Node {
public String getTarget();
public String getText();
public String getValue(String name);
public Map<String, String> getValues();
public boolean removeValue(String name);
public void setTarget(String target);
public void setValue(String name, String value);
public void setValues(Map<String, String> data);
}

View File

@ -0,0 +1,36 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.xml;
import java.io.Serializable;
/**
* @author Brian Wing Shun Chan
*/
public interface QName extends Serializable {
public String getLocalPart();
public String getName();
public Namespace getNamespace();
public String getNamespacePrefix();
public String getNamespaceURI();
public String getQualifiedName();
}

View File

@ -0,0 +1,108 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.xml;
import java.io.File;
import java.io.InputStream;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
/**
* @author Brian Wing Shun Chan
*/
public interface SAXReader {
public Attribute createAttribute(
Element element, QName qName, String value);
public Attribute createAttribute(
Element element, String name, String value);
public Document createDocument();
public Document createDocument(Element rootElement);
public Document createDocument(String encoding);
public Element createElement(QName qName);
public Element createElement(String name);
public Entity createEntity(String name, String text);
public ProcessingInstruction createProcessingInstruction(
String target, Map<String, String> data);
public ProcessingInstruction createProcessingInstruction(
String target, String data);
public Namespace createNamespace(String uri);
public Namespace createNamespace(String prefix, String uri);
public QName createQName(String localName);
public QName createQName(String localName, Namespace namespace);
public Text createText(String text);
public XPath createXPath(String xpathExpression);
public Document read(File file) throws DocumentException;
public Document read(File file, boolean validate)
throws DocumentException;
public Document read(InputStream is) throws DocumentException;
public Document read(InputStream is, boolean validate)
throws DocumentException;
public Document read(Reader reader) throws DocumentException;
public Document read(Reader reader, boolean validate)
throws DocumentException;
public Document read(String xml) throws DocumentException;
public Document read(String xml, boolean validate)
throws DocumentException;
public Document read(URL url) throws DocumentException;
public Document read(URL url, boolean validate) throws DocumentException;
public Document readURL(String url)
throws DocumentException, MalformedURLException;
public Document readURL(String url, boolean validate)
throws DocumentException, MalformedURLException;
public List<Node> selectNodes(
String xpathFilterExpression, List<Node> nodes);
public List<Node> selectNodes(String xpathFilterExpression, Node node);
public void sort(List<Node> nodes, String xpathExpression);
public void sort(
List<Node> nodes, String xpathExpression, boolean distinct);
}

View File

@ -0,0 +1,199 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.xml;
import java.io.File;
import java.io.InputStream;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
/**
* @author Brian Wing Shun Chan
*/
public class SAXReaderUtil {
public static Attribute createAttribute(
Element element, QName qName, String value) {
return getSAXReader().createAttribute(element, qName, value);
}
public static Attribute createAttribute(
Element element, String name, String value) {
return getSAXReader().createAttribute(element, name, value);
}
public static Document createDocument() {
return getSAXReader().createDocument();
}
public static Document createDocument(Element rootElement) {
return getSAXReader().createDocument(rootElement);
}
public static Document createDocument(String encoding) {
return getSAXReader().createDocument(encoding);
}
public static Element createElement(QName qName) {
return getSAXReader().createElement(qName);
}
public static Element createElement(String name) {
return getSAXReader().createElement(name);
}
public static Entity createEntity(String name, String text) {
return getSAXReader().createEntity(name, text);
}
public static Namespace createNamespace(String uri) {
return getSAXReader().createNamespace(uri);
}
public static Namespace createNamespace(String prefix, String uri) {
return getSAXReader().createNamespace(prefix, uri);
}
public static ProcessingInstruction createProcessingInstruction(
String target, Map<String, String> data) {
return getSAXReader().createProcessingInstruction(target, data);
}
public static ProcessingInstruction createProcessingInstruction(
String target, String data) {
return getSAXReader().createProcessingInstruction(target, data);
}
public static QName createQName(String localName) {
return getSAXReader().createQName(localName);
}
public static QName createQName(String localName, Namespace namespace) {
return getSAXReader().createQName(localName, namespace);
}
public static Text createText(String text) {
return getSAXReader().createText(text);
}
public static XPath createXPath(String xpathExpression) {
return getSAXReader().createXPath(xpathExpression);
}
public static SAXReader getSAXReader() {
return _saxReader;
}
public static Document read(File file) throws DocumentException {
return getSAXReader().read(file);
}
public static Document read(File file, boolean validate)
throws DocumentException {
return getSAXReader().read(file, validate);
}
public static Document read(InputStream is) throws DocumentException {
return getSAXReader().read(is);
}
public static Document read(InputStream is, boolean validate)
throws DocumentException {
return getSAXReader().read(is, validate);
}
public static Document read(Reader reader) throws DocumentException {
return getSAXReader().read(reader);
}
public static Document read(Reader reader, boolean validate)
throws DocumentException {
return getSAXReader().read(reader, validate);
}
public static Document read(String xml) throws DocumentException {
return getSAXReader().read(xml);
}
public static Document read(String xml, boolean validate)
throws DocumentException {
return getSAXReader().read(xml, validate);
}
public static Document read(URL url) throws DocumentException {
return getSAXReader().read(url);
}
public static Document read(URL url, boolean validate)
throws DocumentException {
return getSAXReader().read(url, validate);
}
public static Document readURL(String url)
throws DocumentException, MalformedURLException {
return getSAXReader().readURL(url);
}
public static Document readURL(String url, boolean validate)
throws DocumentException, MalformedURLException {
return getSAXReader().readURL(url, validate);
}
public static List<Node> selectNodes(
String xpathFilterExpression, List<Node> nodes) {
return getSAXReader().selectNodes(xpathFilterExpression, nodes);
}
public static List<Node> selectNodes(
String xpathFilterExpression, Node node) {
return getSAXReader().selectNodes(xpathFilterExpression, node);
}
public static void sort(List<Node> nodes, String xpathExpression) {
getSAXReader().sort(nodes, xpathExpression);
}
public static void sort(
List<Node> nodes, String xpathExpression, boolean distinct) {
getSAXReader().sort(nodes, xpathExpression, distinct);
}
public void setSAXReader(SAXReader saxReader) {
_saxReader = saxReader;
}
private static SAXReader _saxReader;
}

View File

@ -0,0 +1,21 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.xml;
/**
* @author Brian Wing Shun Chan
*/
public interface Text extends Node {
}

View File

@ -0,0 +1,51 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.kernel.xml;
import java.io.Serializable;
import java.util.List;
/**
* @author Brian Wing Shun Chan
*/
public interface XPath extends Serializable {
public boolean booleanValueOf(Object context);
public Object evaluate(Object context);
public String getText();
public boolean matches(Node node);
public Number numberValueOf(Object context);
public List<Node> selectNodes(Object context);
public List<Node> selectNodes(Object context, XPath sortXPath);
public List<Node> selectNodes(
Object context, XPath sortXPath, boolean distinct);
public Node selectSingleNode(Object context);
public void sort(List<Node> nodes);
public void sort(List<Node> nodes, boolean distinct);
public String valueOf(Object context);
}

View File

@ -0,0 +1,480 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.util;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.KeyValuePair;
import java.io.InputStream;
import org.xml.sax.InputSource;
/**
* @author Brian Wing Shun Chan
*/
public class EntityResolver implements org.xml.sax.EntityResolver {
public InputSource resolveEntity(String publicId, String systemId) {
ClassLoader classLoader = getClass().getClassLoader();
if (_log.isDebugEnabled()) {
_log.debug("Resolving entity " + publicId + " " + systemId);
}
if (publicId != null) {
for (int i = 0; i < _PUBLIC_IDS.length; i++) {
KeyValuePair kvp = _PUBLIC_IDS[i];
if (publicId.equals(kvp.getKey())) {
InputStream is = classLoader.getResourceAsStream(
_DEFINITIONS_PATH + kvp.getValue());
if (_log.isDebugEnabled()) {
_log.debug("Entity found for public id " + systemId);
}
return new InputSource(is);
}
}
}
else if (systemId != null) {
for (int i = 0; i < _SYSTEM_IDS.length; i++) {
KeyValuePair kvp = _SYSTEM_IDS[i];
if (systemId.equals(kvp.getKey())) {
InputStream is = classLoader.getResourceAsStream(
_DEFINITIONS_PATH + kvp.getValue());
if (_log.isDebugEnabled()) {
_log.debug("Entity found for system id " + systemId);
}
return new InputSource(is);
}
}
}
if (_log.isDebugEnabled()) {
_log.debug("No entity found for " + publicId + " " + systemId);
}
return null;
}
private static String _DEFINITIONS_PATH = "com/liferay/portal/definitions/";
private static KeyValuePair[] _PUBLIC_IDS = {
new KeyValuePair(
"datatypes",
"datatypes.dtd"
),
new KeyValuePair(
"-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN",
"facelet-taglib_1_0.dtd"
),
new KeyValuePair(
"-//Hibernate/Hibernate Mapping DTD 3.0//EN",
"hibernate-mapping-3.0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Display 2.0.0//EN",
"liferay-display_2_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Display 3.5.0//EN",
"liferay-display_3_5_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Display 4.0.0//EN",
"liferay-display_4_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Display 5.0.0//EN",
"liferay-display_5_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Display 5.1.0//EN",
"liferay-display_5_1_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Display 5.2.0//EN",
"liferay-display_5_2_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Display 6.0.0//EN",
"liferay-display_6_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Friendly URL Routes 6.0.0//EN",
"liferay-friendly-url-routes_6_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Hook 5.1.0//EN",
"liferay-hook_5_1_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Hook 5.2.0//EN",
"liferay-hook_5_2_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Hook 6.0.0//EN",
"liferay-hook_6_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Layout Templates 3.6.0//EN",
"liferay-layout-templates_3_6_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Layout Templates 4.0.0//EN",
"liferay-layout-templates_4_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Layout Templates 4.3.0//EN",
"liferay-layout-templates_4_3_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Layout Templates 5.0.0//EN",
"liferay-layout-templates_5_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Layout Templates 5.1.0//EN",
"liferay-layout-templates_5_1_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Layout Templates 5.2.0//EN",
"liferay-layout-templates_5_2_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Layout Templates 6.0.0//EN",
"liferay-layout-templates_6_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Look and Feel 3.5.0//EN",
"liferay-look-and-feel_3_5_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Look and Feel 4.0.0//EN",
"liferay-look-and-feel_4_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Look and Feel 4.3.0//EN",
"liferay-look-and-feel_4_3_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Look and Feel 5.0.0//EN",
"liferay-look-and-feel_5_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Look and Feel 5.1.0//EN",
"liferay-look-and-feel_5_1_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Look and Feel 5.2.0//EN",
"liferay-look-and-feel_5_2_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Look and Feel 6.0.0//EN",
"liferay-look-and-feel_6_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Plugin Package 4.3.0//EN",
"liferay-plugin-package_4_3_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Plugin Package 5.0.0//EN",
"liferay-plugin-package_5_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Plugin Package 5.1.0//EN",
"liferay-plugin-package_5_1_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Plugin Package 5.2.0//EN",
"liferay-plugin-package_5_2_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Plugin Package 6.0.0//EN",
"liferay-plugin-package_6_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Plugin Repository 4.3.0//EN",
"liferay-plugin-repository_4_3_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Plugin Repository 5.0.0//EN",
"liferay-plugin-repository_5_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Plugin Repository 5.1.0//EN",
"liferay-plugin-repository_5_1_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Plugin Repository 5.2.0//EN",
"liferay-plugin-repository_5_2_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Plugin Repository 6.0.0//EN",
"liferay-plugin-repository_6_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Portlet Application 3.5.0//EN",
"liferay-portlet-app_3_5_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Portlet Application 4.0.0//EN",
"liferay-portlet-app_4_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Portlet Application 4.1.0//EN",
"liferay-portlet-app_4_1_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Portlet Application 4.2.0//EN",
"liferay-portlet-app_4_2_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Portlet Application 4.3.0//EN",
"liferay-portlet-app_4_3_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Portlet Application 4.3.1//EN",
"liferay-portlet-app_4_3_1.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Portlet Application 4.3.2//EN",
"liferay-portlet-app_4_3_2.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Portlet Application 4.3.3//EN",
"liferay-portlet-app_4_3_3.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Portlet Application 4.3.6//EN",
"liferay-portlet-app_4_3_6.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Portlet Application 4.4.0//EN",
"liferay-portlet-app_4_4_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Portlet Application 5.0.0//EN",
"liferay-portlet-app_5_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Portlet Application 5.1.0//EN",
"liferay-portlet-app_5_1_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Portlet Application 5.2.0//EN",
"liferay-portlet-app_5_2_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Portlet Application 6.0.0//EN",
"liferay-portlet-app_6_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Service Builder 3.5.0//EN",
"liferay-service-builder_3_5_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Service Builder 3.6.1//EN",
"liferay-service-builder_3_6_1.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Service Builder 4.0.0//EN",
"liferay-service-builder_4_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Service Builder 4.2.0//EN",
"liferay-service-builder_4_2_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Service Builder 4.3.0//EN",
"liferay-service-builder_4_3_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Service Builder 4.3.3//EN",
"liferay-service-builder_4_3_3.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Service Builder 4.4.0//EN",
"liferay-service-builder_4_4_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Service Builder 5.0.0//EN",
"liferay-service-builder_5_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Service Builder 5.1.0//EN",
"liferay-service-builder_5_1_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Service Builder 5.2.0//EN",
"liferay-service-builder_5_2_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Service Builder 6.0.0//EN",
"liferay-service-builder_6_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Theme Loader 4.3.0//EN",
"liferay-theme-loader_4_3_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Theme Loader 5.0.0//EN",
"liferay-theme-loader_5_0_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Theme Loader 5.1.0//EN",
"liferay-theme-loader_5_1_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Theme Loader 5.2.0//EN",
"liferay-theme-loader_5_2_0.dtd"
),
new KeyValuePair(
"-//Liferay//DTD Theme Loader 6.0.0//EN",
"liferay-theme-loader_6_0_0.dtd"
),
new KeyValuePair(
"-//MuleSource //DTD mule-configuration XML V1.0//EN",
"mule-configuration.dtd"
),
new KeyValuePair(
"-//SPRING//DTD BEAN//EN",
"spring-beans.dtd"
),
new KeyValuePair(
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN",
"struts-config_1_2.dtd"
),
new KeyValuePair(
"-//Apache Software Foundation//DTD Tiles Configuration 1.1//EN",
"tiles-config_1_1.dtd"
),
new KeyValuePair(
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN",
"web-app_2_3.dtd"
),
new KeyValuePair(
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN",
"web-facesconfig_1_0.dtd"
),
new KeyValuePair(
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN",
"web-facesconfig_1_1.dtd"
),
new KeyValuePair(
"-//W3C//DTD XMLSCHEMA 200102//EN",
"XMLSchema.dtd"
)
};
private static KeyValuePair[] _SYSTEM_IDS = {
new KeyValuePair(
"http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd",
"portlet-app_1_0.xsd"
),
new KeyValuePair(
"http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd",
"portlet-app_2_0.xsd"
),
new KeyValuePair(
"http://www.w3.org/2001/xml.xsd",
"xml.xsd"
)
};
private static Log _log = LogFactoryUtil.getLog(EntityResolver.class);
}

View File

@ -0,0 +1,109 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.xml;
import com.liferay.portal.kernel.xml.Attribute;
import com.liferay.portal.kernel.xml.Namespace;
import com.liferay.portal.kernel.xml.QName;
/**
* @author Brian Wing Shun Chan
*/
public class AttributeImpl extends NodeImpl implements Attribute {
public AttributeImpl(org.dom4j.Attribute attribute) {
super(attribute);
_attribute = attribute;
}
public Object getData() {
return _attribute.getData();
}
public boolean equals(Object obj) {
org.dom4j.Attribute attribute =
((AttributeImpl)obj).getWrappedAttribute();
return _attribute.equals(attribute);
}
public Namespace getNamespace() {
org.dom4j.Namespace namespace = _attribute.getNamespace();
if (namespace == null) {
return null;
}
else {
return new NamespaceImpl(namespace);
}
}
public String getNamespacePrefix() {
return _attribute.getNamespacePrefix();
}
public String getNamespaceURI() {
return _attribute.getNamespaceURI();
}
public QName getQName() {
org.dom4j.QName qName = _attribute.getQName();
if (qName == null) {
return null;
}
else {
return new QNameImpl(qName);
}
}
public String getQualifiedName() {
return _attribute.getQualifiedName();
}
public String getValue() {
return _attribute.getValue();
}
public org.dom4j.Attribute getWrappedAttribute() {
return _attribute;
}
public int hashCode() {
return _attribute.hashCode();
}
public void setData(Object data) {
_attribute.setData(data);
}
public void setNamespace(Namespace namespace) {
NamespaceImpl namespaceImpl = (NamespaceImpl)namespace;
_attribute.setNamespace(namespaceImpl.getWrappedNamespace());
}
public void setValue(String value) {
_attribute.setValue(value);
}
public String toString() {
return _attribute.toString();
}
private org.dom4j.Attribute _attribute;
}

View File

@ -0,0 +1,213 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.xml;
import com.liferay.portal.kernel.xml.Branch;
import com.liferay.portal.kernel.xml.Comment;
import com.liferay.portal.kernel.xml.Element;
import com.liferay.portal.kernel.xml.Node;
import com.liferay.portal.kernel.xml.ProcessingInstruction;
import com.liferay.portal.kernel.xml.QName;
import java.util.Iterator;
import java.util.List;
/**
* @author Brian Wing Shun Chan
*/
public class BranchImpl extends NodeImpl implements Branch {
public BranchImpl(org.dom4j.Branch branch) {
super(branch);
_branch = branch;
}
public void add(Comment comment) {
CommentImpl commentImpl = (CommentImpl)comment;
_branch.add(commentImpl.getWrappedComment());
}
public void add(Element element) {
ElementImpl elementImpl = (ElementImpl)element;
_branch.add(elementImpl.getWrappedElement());
}
public void add(Node node) {
NodeImpl nodeImpl = (NodeImpl)node;
_branch.add(nodeImpl.getWrappedNode());
}
public void add(ProcessingInstruction processingInstruction) {
ProcessingInstructionImpl processingInstructionImpl =
(ProcessingInstructionImpl)processingInstruction;
_branch.add(
processingInstructionImpl.getWrappedProcessingInstruction());
}
public Element addElement(QName qName) {
QNameImpl qNameImpl = (QNameImpl)qName;
return new ElementImpl(_branch.addElement(qNameImpl.getWrappedQName()));
}
public Element addElement(String name) {
return new ElementImpl(_branch.addElement(name));
}
public Element addElement(String qualifiedName, String namespaceURI) {
return new ElementImpl(_branch.addElement(qualifiedName, namespaceURI));
}
public void appendContent(Branch branch) {
BranchImpl branchImpl = (BranchImpl)branch;
_branch.appendContent(branchImpl.getWrappedBranch());
}
public void clearContent() {
_branch.clearContent();
}
public List<Node> content() {
return SAXReaderImpl.toNewNodes(_branch.content());
}
public Element elementByID(String elementID) {
return new ElementImpl(_branch.elementByID(elementID));
}
public boolean equals(Object obj) {
org.dom4j.Branch branch = ((BranchImpl)obj).getWrappedBranch();
return _branch.equals(branch);
}
public org.dom4j.Branch getWrappedBranch() {
return _branch;
}
public int hashCode() {
return _branch.hashCode();
}
public int indexOf(Node node) {
NodeImpl nodeImpl = (NodeImpl)node;
return _branch.indexOf(nodeImpl.getWrappedNode());
}
public Node node(int index) {
org.dom4j.Node node = _branch.node(index);
if (node == null) {
return null;
}
else {
if (node instanceof org.dom4j.Element) {
return new ElementImpl((org.dom4j.Element)node);
}
else {
return new NodeImpl(node);
}
}
}
public int nodeCount() {
return _branch.nodeCount();
}
public Iterator<Node> nodeIterator() {
return content().iterator();
}
public void normalize() {
_branch.normalize();
}
public ProcessingInstruction processingInstruction(String target) {
org.dom4j.ProcessingInstruction processingInstruction =
_branch.processingInstruction(target);
if (processingInstruction == null) {
return null;
}
else {
return new ProcessingInstructionImpl(processingInstruction);
}
}
public List<ProcessingInstruction> processingInstructions() {
return SAXReaderImpl.toNewProcessingInstructions(
_branch.processingInstructions());
}
public List<ProcessingInstruction> processingInstructions(String target) {
return SAXReaderImpl.toNewProcessingInstructions(
_branch.processingInstructions(target));
}
public boolean remove(Comment comment) {
CommentImpl commentImpl = (CommentImpl)comment;
return _branch.remove(commentImpl.getWrappedComment());
}
public boolean remove(Element element) {
ElementImpl elementImpl = (ElementImpl)element;
return _branch.remove(elementImpl.getWrappedElement());
}
public boolean remove(Node node) {
NodeImpl nodeImpl = (NodeImpl)node;
return _branch.remove(nodeImpl.getWrappedNode());
}
public boolean remove(ProcessingInstruction processingInstruction) {
ProcessingInstructionImpl processingInstructionImpl =
(ProcessingInstructionImpl)processingInstruction;
return _branch.remove(
processingInstructionImpl.getWrappedProcessingInstruction());
}
public boolean removeProcessingInstruction(String target) {
return _branch.removeProcessingInstruction(target);
}
public void setContent(List<Node> content) {
_branch.setContent(SAXReaderImpl.toOldNodes(content));
}
public void setProcessingInstructions(
List<ProcessingInstruction> processingInstructions) {
_branch.setProcessingInstructions(
SAXReaderImpl.toOldProcessingInstructions(processingInstructions));
}
public String toString() {
return _branch.toString();
}
private org.dom4j.Branch _branch;
}

View File

@ -0,0 +1,50 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.xml;
import com.liferay.portal.kernel.xml.CDATA;
/**
* @author Brian Wing Shun Chan
*/
public class CDATAImpl extends NodeImpl implements CDATA {
public CDATAImpl(org.dom4j.CDATA cdata) {
super(cdata);
_cdata = cdata;
}
public boolean equals(Object obj) {
org.dom4j.CDATA cdata = ((CDATAImpl)obj).getWrappedCDATA();
return _cdata.equals(cdata);
}
public org.dom4j.CDATA getWrappedCDATA() {
return _cdata;
}
public int hashCode() {
return _cdata.hashCode();
}
public String toString() {
return _cdata.toString();
}
private org.dom4j.CDATA _cdata;
}

View File

@ -0,0 +1,50 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.xml;
import com.liferay.portal.kernel.xml.Comment;
/**
* @author Brian Wing Shun Chan
*/
public class CommentImpl extends NodeImpl implements Comment {
public CommentImpl(org.dom4j.Comment comment) {
super(comment);
_comment = comment;
}
public boolean equals(Object obj) {
org.dom4j.Comment comment = ((CommentImpl)obj).getWrappedComment();
return _comment.equals(comment);
}
public org.dom4j.Comment getWrappedComment() {
return _comment;
}
public int hashCode() {
return _comment.hashCode();
}
public String toString() {
return _comment.toString();
}
private org.dom4j.Comment _comment;
}

View File

@ -0,0 +1,98 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.xml;
import com.liferay.portal.kernel.xml.Document;
import com.liferay.portal.kernel.xml.Element;
import com.liferay.util.xml.XMLFormatter;
import java.io.IOException;
/**
* @author Brian Wing Shun Chan
*/
public class DocumentImpl extends BranchImpl implements Document {
public DocumentImpl(org.dom4j.Document document) {
super(document);
_document = document;
}
public Document addComment(String comment) {
_document.addComment(comment);
return this;
}
public Document addDocType(String name, String publicId, String systemId) {
_document.addDocType(name, publicId, systemId);
return this;
}
public boolean equals(Object obj) {
org.dom4j.Document document = ((DocumentImpl)obj).getWrappedDocument();
return _document.equals(document);
}
public String formattedString() throws IOException {
return XMLFormatter.toString(_document);
}
public String formattedString(String indent) throws IOException {
return XMLFormatter.toString(_document, indent);
}
public String formattedString(String indent, boolean expandEmptyElements)
throws IOException {
return XMLFormatter.toString(_document, indent, expandEmptyElements);
}
public Element getRootElement() {
return new ElementImpl(_document.getRootElement());
}
public org.dom4j.Document getWrappedDocument() {
return _document;
}
public String getXMLEncoding() {
return _document.getXMLEncoding();
}
public int hashCode() {
return _document.hashCode();
}
public void setRootElement(Element rootElement) {
ElementImpl rootElementImpl = (ElementImpl)rootElement;
_document.setRootElement(rootElementImpl.getWrappedElement());
}
public void setXMLEncoding(String encoding) {
_document.setXMLEncoding(encoding);
}
public String toString() {
return _document.toString();
}
private org.dom4j.Document _document;
}

View File

@ -0,0 +1,451 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.xml;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.xml.Attribute;
import com.liferay.portal.kernel.xml.CDATA;
import com.liferay.portal.kernel.xml.Element;
import com.liferay.portal.kernel.xml.Entity;
import com.liferay.portal.kernel.xml.Namespace;
import com.liferay.portal.kernel.xml.Node;
import com.liferay.portal.kernel.xml.QName;
import com.liferay.portal.kernel.xml.Text;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* @author Brian Wing Shun Chan
*/
public class ElementImpl extends BranchImpl implements Element {
public ElementImpl(org.dom4j.Element element) {
super(element);
_element = element;
}
public void add(Attribute attribute) {
AttributeImpl attributeImpl = (AttributeImpl)attribute;
_element.add(attributeImpl.getWrappedAttribute());
}
public void add(CDATA cdata) {
CDATAImpl cdataImpl = (CDATAImpl)cdata;
_element.add(cdataImpl.getWrappedCDATA());
}
public void add(Entity entity) {
EntityImpl entityImpl = (EntityImpl)entity;
_element.add(entityImpl.getWrappedEntity());
}
public void add(Namespace namespace) {
NamespaceImpl namespaceImpl = (NamespaceImpl)namespace;
_element.add(namespaceImpl.getWrappedNamespace());
}
public void add(Text text) {
TextImpl textImpl = (TextImpl)text;
_element.add(textImpl.getWrappedText());
}
public Element addAttribute(QName qName, String value) {
QNameImpl qNameImpl = (QNameImpl)qName;
return new ElementImpl(
_element.addAttribute(qNameImpl.getWrappedQName(), value));
}
public Element addAttribute(String name, String value) {
return new ElementImpl(_element.addAttribute(name, value));
}
public Element addCDATA(String cdata) {
cdata = StringUtil.replace(cdata, "]]>", "]]]]><![CDATA[>");
return new ElementImpl(_element.addCDATA(cdata));
}
public Element addComment(String comment) {
return new ElementImpl(_element.addComment(comment));
}
public Element addEntity(String name, String text) {
return new ElementImpl(_element.addEntity(name, text));
}
public Element addNamespace(String prefix, String uri) {
return new ElementImpl(_element.addNamespace(prefix, uri));
}
public Element addProcessingInstruction(
String target, Map<String, String> data) {
return new ElementImpl(_element.addProcessingInstruction(target, data));
}
public Element addProcessingInstruction(String target, String data) {
return new ElementImpl(_element.addProcessingInstruction(target, data));
}
public Element addText(String text) {
return new ElementImpl(_element.addText(text));
}
public List<Namespace> additionalNamespaces() {
return SAXReaderImpl.toNewNamespaces(_element.additionalNamespaces());
}
public void appendAttributes(Element element) {
ElementImpl elementImpl = (ElementImpl)element;
_element.appendAttributes(elementImpl.getWrappedElement());
}
public Attribute attribute(int index) {
org.dom4j.Attribute attribute = _element.attribute(index);
if (attribute == null) {
return null;
}
else {
return new AttributeImpl(attribute);
}
}
public Attribute attribute(QName qName) {
QNameImpl qNameImpl = (QNameImpl)qName;
org.dom4j.Attribute attribute = _element.attribute(
qNameImpl.getWrappedQName());
if (attribute == null) {
return null;
}
else {
return new AttributeImpl(attribute);
}
}
public Attribute attribute(String name) {
org.dom4j.Attribute attribute = _element.attribute(name);
if (attribute == null) {
return null;
}
else {
return new AttributeImpl(attribute);
}
}
public int attributeCount() {
return _element.attributeCount();
}
public Iterator<Attribute> attributeIterator() {
return attributes().iterator();
}
public String attributeValue(QName qName) {
QNameImpl qNameImpl = (QNameImpl)qName;
return _element.attributeValue(qNameImpl.getWrappedQName());
}
public String attributeValue(QName qName, String defaultValue) {
QNameImpl qNameImpl = (QNameImpl)qName;
return _element.attributeValue(
qNameImpl.getWrappedQName(), defaultValue);
}
public String attributeValue(String name) {
return _element.attributeValue(name);
}
public String attributeValue(String name, String defaultValue) {
return _element.attributeValue(name, defaultValue);
}
public List<Attribute> attributes() {
return SAXReaderImpl.toNewAttributes(_element.attributes());
}
public Element createCopy() {
return new ElementImpl(_element.createCopy());
}
public Element createCopy(QName qName) {
QNameImpl qNameImpl = (QNameImpl)qName;
return new ElementImpl(
_element.createCopy(qNameImpl.getWrappedQName()));
}
public Element createCopy(String name) {
return new ElementImpl(_element.createCopy(name));
}
public List<Namespace> declaredNamespaces() {
return SAXReaderImpl.toNewNamespaces(_element.declaredNamespaces());
}
public Element element(QName qName) {
QNameImpl qNameImpl = (QNameImpl)qName;
org.dom4j.Element element = _element.element(
qNameImpl.getWrappedQName());
if (element == null) {
return null;
}
else {
return new ElementImpl(element);
}
}
public Element element(String name) {
org.dom4j.Element element = _element.element(name);
if (element == null) {
return null;
}
else {
return new ElementImpl(element);
}
}
public Iterator<Element> elementIterator() {
return elements().iterator();
}
public Iterator<Element> elementIterator(QName qName) {
return elements(qName).iterator();
}
public Iterator<Element> elementIterator(String name) {
return elements(name).iterator();
}
public String elementText(QName qName) {
QNameImpl qNameImpl = (QNameImpl)qName;
return _element.elementText(qNameImpl.getWrappedQName());
}
public String elementText(String name) {
return _element.elementText(name);
}
public String elementTextTrim(QName qName) {
QNameImpl qNameImpl = (QNameImpl)qName;
return _element.elementTextTrim(qNameImpl.getWrappedQName());
}
public String elementTextTrim(String name) {
return _element.elementTextTrim(name);
}
public List<Element> elements() {
return SAXReaderImpl.toNewElements(_element.elements());
}
public List<Element> elements(QName qName) {
QNameImpl qNameImpl = (QNameImpl)qName;
return SAXReaderImpl.toNewElements(
_element.elements(qNameImpl.getWrappedQName()));
}
public List<Element> elements(String name) {
return SAXReaderImpl.toNewElements(_element.elements(name));
}
public boolean equals(Object obj) {
org.dom4j.Element element = ((ElementImpl)obj).getWrappedElement();
return _element.equals(element);
}
public Object getData() {
return _element.getData();
}
public Namespace getNamespace() {
org.dom4j.Namespace namespace = _element.getNamespace();
if (namespace == null) {
return null;
}
else {
return new NamespaceImpl(namespace);
}
}
public Namespace getNamespaceForPrefix(String prefix) {
org.dom4j.Namespace namespace = _element.getNamespaceForPrefix(prefix);
if (namespace == null) {
return null;
}
else {
return new NamespaceImpl(namespace);
}
}
public Namespace getNamespaceForURI(String uri) {
org.dom4j.Namespace namespace = _element.getNamespaceForURI(uri);
if (namespace == null) {
return null;
}
else {
return new NamespaceImpl(namespace);
}
}
public String getNamespacePrefix() {
return _element.getNamespacePrefix();
}
public String getNamespaceURI() {
return _element.getNamespaceURI();
}
public List<Namespace> getNamespacesForURI(String uri) {
return SAXReaderImpl.toNewNamespaces(_element.getNamespacesForURI(uri));
}
public QName getQName() {
org.dom4j.QName qName = _element.getQName();
if (qName == null) {
return null;
}
else {
return new QNameImpl(qName);
}
}
public QName getQName(String qualifiedName) {
org.dom4j.QName qName = _element.getQName(qualifiedName);
if (qName == null) {
return null;
}
else {
return new QNameImpl(qName);
}
}
public String getQualifiedName() {
return _element.getQualifiedName();
}
public String getTextTrim() {
return _element.getTextTrim();
}
public org.dom4j.Element getWrappedElement() {
return _element;
}
public Node getXPathResult(int index) {
org.dom4j.Node node = _element.getXPathResult(index);
if (node == null) {
return null;
}
else {
return new NodeImpl(node);
}
}
public int hashCode() {
return _element.hashCode();
}
public boolean hasMixedContent() {
return _element.hasMixedContent();
}
public boolean isRootElement() {
return _element.isRootElement();
}
public boolean isTextOnly() {
return _element.isTextOnly();
}
public boolean remove(Attribute attribute) {
AttributeImpl attributeImpl = (AttributeImpl)attribute;
return _element.remove(attributeImpl.getWrappedAttribute());
}
public boolean remove(CDATA cdata) {
CDATAImpl cdataImpl = (CDATAImpl)cdata;
return _element.remove(cdataImpl.getWrappedCDATA());
}
public boolean remove(Entity entity) {
EntityImpl entityImpl = (EntityImpl)entity;
return _element.remove(entityImpl.getWrappedEntity());
}
public boolean remove(Namespace namespace) {
NamespaceImpl namespaceImpl = (NamespaceImpl)namespace;
return _element.remove(namespaceImpl.getWrappedNamespace());
}
public boolean remove(Text text) {
TextImpl textImpl = (TextImpl)text;
return _element.remove(textImpl.getWrappedText());
}
public void setAttributes(List<Attribute> attributes) {
_element.setAttributes(SAXReaderImpl.toOldAttributes(attributes));
}
public void setData(Object data) {
_element.setData(data);
}
public void setQName(QName qName) {
QNameImpl qNameImpl = (QNameImpl)qName;
_element.setQName(qNameImpl.getWrappedQName());
}
public String toString() {
return _element.toString();
}
private org.dom4j.Element _element;
}

View File

@ -0,0 +1,50 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.xml;
import com.liferay.portal.kernel.xml.Entity;
/**
* @author Brian Wing Shun Chan
*/
public class EntityImpl extends NodeImpl implements Entity {
public EntityImpl(org.dom4j.Entity entity) {
super(entity);
_entity = entity;
}
public boolean equals(Object obj) {
org.dom4j.Entity entity = ((EntityImpl)obj).getWrappedEntity();
return _entity.equals(entity);
}
public org.dom4j.Entity getWrappedEntity() {
return _entity;
}
public int hashCode() {
return _entity.hashCode();
}
public String toString() {
return _entity.toString();
}
private org.dom4j.Entity _entity;
}

View File

@ -0,0 +1,67 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.xml;
import com.liferay.portal.kernel.xml.Namespace;
/**
* @author Brian Wing Shun Chan
*/
public class NamespaceImpl extends NodeImpl implements Namespace {
public NamespaceImpl(org.dom4j.Namespace namespace) {
super(namespace);
_namespace = namespace;
}
public boolean equals(Object obj) {
org.dom4j.Namespace namespace =
((NamespaceImpl)obj).getWrappedNamespace();
return _namespace.equals(namespace);
}
public short getNodeType() {
return _namespace.getNodeType();
}
public String getPrefix() {
return _namespace.getPrefix();
}
public String getURI() {
return _namespace.getURI();
}
public org.dom4j.Namespace getWrappedNamespace() {
return _namespace;
}
public String getXPathNameStep() {
return _namespace.getXPathNameStep();
}
public int hashCode() {
return _namespace.hashCode();
}
public String toString() {
return _namespace.toString();
}
private org.dom4j.Namespace _namespace;
}

View File

@ -0,0 +1,228 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.xml;
import com.liferay.portal.kernel.xml.Document;
import com.liferay.portal.kernel.xml.Element;
import com.liferay.portal.kernel.xml.Node;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
/**
* @author Brian Wing Shun Chan
*/
public class NodeImpl implements Node {
public NodeImpl(org.dom4j.Node node) {
_node = node;
}
public String asXML() {
return _node.asXML();
}
public Node asXPathResult(Element parent) {
ElementImpl parentImpl = (ElementImpl)parent;
org.dom4j.Node node = _node.asXPathResult(
parentImpl.getWrappedElement());
if (node == null) {
return null;
}
if (node instanceof org.dom4j.Element) {
return new ElementImpl((org.dom4j.Element)node);
}
else {
return new NodeImpl(node);
}
}
public Node detach() {
org.dom4j.Node node = _node.detach();
if (node == null) {
return null;
}
if (node instanceof org.dom4j.Element) {
return new ElementImpl((org.dom4j.Element)node);
}
else {
return new NodeImpl(node);
}
}
public boolean equals(Object obj) {
org.dom4j.Node node = ((NodeImpl)obj).getWrappedNode();
return _node.equals(node);
}
public Document getDocument() {
org.dom4j.Document document = _node.getDocument();
if (document == null) {
return null;
}
else {
return new DocumentImpl(document);
}
}
public String getName() {
return _node.getName();
}
public Element getParent() {
org.dom4j.Element element = _node.getParent();
if (element == null) {
return null;
}
else {
return new ElementImpl(element);
}
}
public String getPath() {
return _node.getPath();
}
public String getPath(Element context) {
ElementImpl contextImpl = (ElementImpl)context;
return _node.getPath(contextImpl.getWrappedElement());
}
public String getStringValue() {
return _node.getStringValue();
}
public String getText() {
return _node.getText();
}
public String getUniquePath() {
return _node.getUniquePath();
}
public String getUniquePath(Element context) {
ElementImpl contextImpl = (ElementImpl)context;
return _node.getUniquePath(contextImpl.getWrappedElement());
}
public org.dom4j.Node getWrappedNode() {
return _node;
}
public boolean hasContent() {
return _node.hasContent();
}
public int hashCode() {
return _node.hashCode();
}
public boolean isReadOnly() {
return _node.isReadOnly();
}
public boolean matches(String xpathExpression) {
return _node.matches(xpathExpression);
}
public Number numberValueOf(String xpathExpression) {
return _node.numberValueOf(xpathExpression);
}
public List<Node> selectNodes(String xpathExpression) {
return SAXReaderImpl.toNewNodes(_node.selectNodes(xpathExpression));
}
public List<Node> selectNodes(
String xpathExpression, String comparisonXPathExpression) {
return SAXReaderImpl.toNewNodes(
_node.selectNodes(xpathExpression, comparisonXPathExpression));
}
public List<Node> selectNodes(
String xpathExpression, String comparisonXPathExpression,
boolean removeDuplicates) {
return SAXReaderImpl.toNewNodes(
_node.selectNodes(
xpathExpression, comparisonXPathExpression, removeDuplicates));
}
public Object selectObject(String xpathExpression) {
Object obj = _node.selectObject(xpathExpression);
if (obj == null) {
return null;
}
else if (obj instanceof List<?>) {
return SAXReaderImpl.toNewNodes((List<org.dom4j.Node>)obj);
}
else {
return obj;
}
}
public Node selectSingleNode(String xpathExpression) {
org.dom4j.Node node = _node.selectSingleNode(xpathExpression);
if (node == null) {
return null;
}
if (node instanceof org.dom4j.Element) {
return new ElementImpl((org.dom4j.Element)node);
}
else {
return new NodeImpl(node);
}
}
public void setName(String name) {
_node.setName(name);
}
public void setText(String text) {
_node.setText(text);
}
public boolean supportsParent() {
return _node.supportsParent();
}
public String toString() {
return _node.toString();
}
public String valueOf(String xpathExpression) {
return _node.valueOf(xpathExpression);
}
public void write(Writer writer) throws IOException {
_node.write(writer);
}
private org.dom4j.Node _node;
}

View File

@ -0,0 +1,121 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.xml;
import com.liferay.portal.kernel.util.TranslatedList;
import com.liferay.portal.kernel.xml.Attribute;
import com.liferay.portal.kernel.xml.Branch;
import com.liferay.portal.kernel.xml.CDATA;
import com.liferay.portal.kernel.xml.Comment;
import com.liferay.portal.kernel.xml.Document;
import com.liferay.portal.kernel.xml.Element;
import com.liferay.portal.kernel.xml.Entity;
import com.liferay.portal.kernel.xml.Namespace;
import com.liferay.portal.kernel.xml.Node;
import com.liferay.portal.kernel.xml.ProcessingInstruction;
import com.liferay.portal.kernel.xml.QName;
import com.liferay.portal.kernel.xml.Text;
import com.liferay.portal.kernel.xml.XPath;
import java.util.List;
/**
* @author Brian Wing Shun Chan
*/
public class NodeList<E, F> extends TranslatedList<E, F> {
public NodeList(List<E> newList, List<F> oldList) {
super(newList, oldList);
}
protected TranslatedList<E, F> newInstance(
List<E> newList, List<F> oldList) {
return new NodeList<E, F>(newList, oldList);
}
protected F toOldObject(E o) {
if (o instanceof Attribute) {
AttributeImpl attributeImpl = (AttributeImpl)o;
return (F)attributeImpl.getWrappedAttribute();
}
else if (o instanceof CDATA) {
CDATAImpl cdataImpl = (CDATAImpl)o;
return (F)cdataImpl.getWrappedCDATA();
}
else if (o instanceof Comment) {
CommentImpl commentImpl = (CommentImpl)o;
return (F)commentImpl.getWrappedComment();
}
else if (o instanceof Document) {
DocumentImpl documentImpl = (DocumentImpl)o;
return (F)documentImpl.getWrappedDocument();
}
else if (o instanceof Element) {
ElementImpl elementImpl = (ElementImpl)o;
return (F)elementImpl.getWrappedElement();
}
else if (o instanceof Entity) {
EntityImpl entityImpl = (EntityImpl)o;
return (F)entityImpl.getWrappedEntity();
}
else if (o instanceof Namespace) {
NamespaceImpl namespaceImpl = (NamespaceImpl)o;
return (F)namespaceImpl.getWrappedNamespace();
}
else if (o instanceof ProcessingInstruction) {
ProcessingInstructionImpl processingInstructionImpl =
(ProcessingInstructionImpl)o;
return
(F)processingInstructionImpl.getWrappedProcessingInstruction();
}
else if (o instanceof QName) {
QNameImpl qNameImpl = (QNameImpl)o;
return (F)qNameImpl.getWrappedQName();
}
else if (o instanceof Text) {
TextImpl textImpl = (TextImpl)o;
return (F)textImpl.getWrappedText();
}
else if (o instanceof XPath) {
XPathImpl xPathImpl = (XPathImpl)o;
return (F)xPathImpl.getWrappedXPath();
}
else if (o instanceof Branch) {
BranchImpl branchImpl = (BranchImpl)o;
return (F)branchImpl.getWrappedBranch();
}
else if (o instanceof Node) {
NodeImpl nodeImpl = (NodeImpl)o;
return (F)nodeImpl.getWrappedNode();
}
throw new IllegalArgumentException(o.getClass().getName());
}
}

View File

@ -0,0 +1,88 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.xml;
import com.liferay.portal.kernel.xml.ProcessingInstruction;
import java.util.Map;
/**
* @author Brian Wing Shun Chan
*/
public class ProcessingInstructionImpl
extends NodeImpl implements ProcessingInstruction {
public ProcessingInstructionImpl(
org.dom4j.ProcessingInstruction processingInstruction) {
super(processingInstruction);
_processingInstruction = processingInstruction;
}
public boolean equals(Object obj) {
org.dom4j.ProcessingInstruction processingInstruction =
((ProcessingInstructionImpl)obj).getWrappedProcessingInstruction();
return _processingInstruction.equals(processingInstruction);
}
public String getTarget() {
return _processingInstruction.getTarget();
}
public String getText() {
return _processingInstruction.getText();
}
public String getValue(String name) {
return _processingInstruction.getValue(name);
}
public Map<String, String> getValues() {
return _processingInstruction.getValues();
}
public org.dom4j.ProcessingInstruction getWrappedProcessingInstruction() {
return _processingInstruction;
}
public int hashCode() {
return _processingInstruction.hashCode();
}
public boolean removeValue(String name) {
return _processingInstruction.removeValue(name);
}
public void setTarget(String target) {
_processingInstruction.setTarget(target);
}
public void setValue(String name, String value) {
_processingInstruction.setValue(name, value);
}
public void setValues(Map<String, String> data) {
_processingInstruction.setValues(data);
}
public String toString() {
return _processingInstruction.toString();
}
private org.dom4j.ProcessingInstruction _processingInstruction;
}

View File

@ -0,0 +1,80 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.xml;
import com.liferay.portal.kernel.xml.Namespace;
import com.liferay.portal.kernel.xml.QName;
/**
* @author Brian Wing Shun Chan
*/
public class QNameImpl implements QName {
public QNameImpl(org.dom4j.QName qName) {
_qName = qName;
}
public boolean equals(Object obj) {
org.dom4j.QName qName = ((QNameImpl)obj).getWrappedQName();
return _qName.equals(qName);
}
public String getLocalPart() {
return getName();
}
public String getName() {
return _qName.getName();
}
public Namespace getNamespace() {
org.dom4j.Namespace namespace = _qName.getNamespace();
if (namespace == null) {
return null;
}
else {
return new NamespaceImpl(namespace);
}
}
public String getNamespacePrefix() {
return _qName.getNamespacePrefix();
}
public String getNamespaceURI() {
return _qName.getNamespaceURI();
}
public String getQualifiedName() {
return _qName.getQualifiedName();
}
public org.dom4j.QName getWrappedQName() {
return _qName;
}
public int hashCode() {
return _qName.hashCode();
}
public String toString() {
return _qName.toString();
}
private org.dom4j.QName _qName;
}

View File

@ -0,0 +1,457 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.xml;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.xml.Attribute;
import com.liferay.portal.kernel.xml.Document;
import com.liferay.portal.kernel.xml.DocumentException;
import com.liferay.portal.kernel.xml.Element;
import com.liferay.portal.kernel.xml.Entity;
import com.liferay.portal.kernel.xml.Namespace;
import com.liferay.portal.kernel.xml.Node;
import com.liferay.portal.kernel.xml.ProcessingInstruction;
import com.liferay.portal.kernel.xml.QName;
import com.liferay.portal.kernel.xml.SAXReader;
import com.liferay.portal.kernel.xml.Text;
import com.liferay.portal.kernel.xml.XPath;
import com.liferay.portal.util.EntityResolver;
import com.liferay.util.xml.XMLSafeReader;
import java.io.File;
import java.io.InputStream;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.xerces.parsers.SAXParser;
import org.dom4j.DocumentFactory;
import org.dom4j.DocumentHelper;
/**
* @author Brian Wing Shun Chan
*/
public class SAXReaderImpl implements SAXReader {
public static SAXReaderImpl getInstance() {
return _instance;
}
public static List<Attribute> toNewAttributes(
List<org.dom4j.Attribute> oldAttributes) {
List<Attribute> newAttributes = new ArrayList<Attribute>(
oldAttributes.size());
for (org.dom4j.Attribute oldAttribute : oldAttributes) {
newAttributes.add(new AttributeImpl(oldAttribute));
}
return new NodeList<Attribute, org.dom4j.Attribute>(
newAttributes, oldAttributes);
}
public static List<Element> toNewElements(
List<org.dom4j.Element> oldElements) {
List<Element> newElements = new ArrayList<Element>(oldElements.size());
for (org.dom4j.Element oldElement : oldElements) {
newElements.add(new ElementImpl(oldElement));
}
return new NodeList<Element, org.dom4j.Element>(
newElements, oldElements);
}
public static List<Namespace> toNewNamespaces(
List<org.dom4j.Namespace> oldNamespaces) {
List<Namespace> newNamespaces = new ArrayList<Namespace>(
oldNamespaces.size());
for (org.dom4j.Namespace oldNamespace : oldNamespaces) {
newNamespaces.add(new NamespaceImpl(oldNamespace));
}
return new NodeList<Namespace, org.dom4j.Namespace>(
newNamespaces, oldNamespaces);
}
public static List<Node> toNewNodes(List<org.dom4j.Node> oldNodes) {
List<Node> newNodes = new ArrayList<Node>(oldNodes.size());
for (org.dom4j.Node oldNode : oldNodes) {
if (oldNode instanceof org.dom4j.Element) {
newNodes.add(new ElementImpl((org.dom4j.Element)oldNode));
}
else {
newNodes.add(new NodeImpl(oldNode));
}
}
return new NodeList<Node, org.dom4j.Node>(newNodes, oldNodes);
}
public static List<ProcessingInstruction> toNewProcessingInstructions(
List<org.dom4j.ProcessingInstruction> oldProcessingInstructions) {
List<ProcessingInstruction> newProcessingInstructions =
new ArrayList<ProcessingInstruction>(
oldProcessingInstructions.size());
for (org.dom4j.ProcessingInstruction oldProcessingInstruction :
oldProcessingInstructions) {
newProcessingInstructions.add(
new ProcessingInstructionImpl(oldProcessingInstruction));
}
return new NodeList
<ProcessingInstruction, org.dom4j.ProcessingInstruction>(
newProcessingInstructions, oldProcessingInstructions);
}
public static List<org.dom4j.Attribute> toOldAttributes(
List<Attribute> newAttributes) {
List<org.dom4j.Attribute> oldAttributes =
new ArrayList<org.dom4j.Attribute>(newAttributes.size());
for (Attribute newAttribute : newAttributes) {
AttributeImpl newAttributeImpl = (AttributeImpl)newAttribute;
oldAttributes.add(newAttributeImpl.getWrappedAttribute());
}
return oldAttributes;
}
public static List<org.dom4j.Node> toOldNodes(List<Node> newNodes) {
List<org.dom4j.Node> oldNodes = new ArrayList<org.dom4j.Node>(
newNodes.size());
for (Node newNode : newNodes) {
NodeImpl newNodeImpl = (NodeImpl)newNode;
oldNodes.add(newNodeImpl.getWrappedNode());
}
return oldNodes;
}
public static List<org.dom4j.ProcessingInstruction>
toOldProcessingInstructions(
List<ProcessingInstruction> newProcessingInstructions) {
List<org.dom4j.ProcessingInstruction> oldProcessingInstructions =
new ArrayList<org.dom4j.ProcessingInstruction>(
newProcessingInstructions.size());
for (ProcessingInstruction newProcessingInstruction :
newProcessingInstructions) {
ProcessingInstructionImpl newProcessingInstructionImpl =
(ProcessingInstructionImpl)newProcessingInstruction;
oldProcessingInstructions.add(
newProcessingInstructionImpl.getWrappedProcessingInstruction());
}
return oldProcessingInstructions;
}
public Attribute createAttribute(
Element element, QName qName, String value) {
ElementImpl elementImpl = (ElementImpl)element;
QNameImpl qNameImpl = (QNameImpl)qName;
DocumentFactory documentFactory = DocumentFactory.getInstance();
return new AttributeImpl(
documentFactory.createAttribute(
elementImpl.getWrappedElement(), qNameImpl.getWrappedQName(),
value));
}
public Attribute createAttribute(
Element element, String name, String value) {
ElementImpl elementImpl = (ElementImpl)element;
DocumentFactory documentFactory = DocumentFactory.getInstance();
return new AttributeImpl(
documentFactory.createAttribute(
elementImpl.getWrappedElement(), name, value));
}
public Document createDocument() {
return new DocumentImpl(DocumentHelper.createDocument());
}
public Document createDocument(Element rootElement) {
ElementImpl rootElementImpl = (ElementImpl)rootElement;
return new DocumentImpl(
DocumentHelper.createDocument(rootElementImpl.getWrappedElement()));
}
public Document createDocument(String encoding) {
DocumentFactory documentFactory = DocumentFactory.getInstance();
return new DocumentImpl(documentFactory.createDocument(encoding));
}
public Element createElement(QName qName) {
QNameImpl qNameImpl = (QNameImpl)qName;
return new ElementImpl(
DocumentHelper.createElement(qNameImpl.getWrappedQName()));
}
public Element createElement(String name) {
return new ElementImpl(DocumentHelper.createElement(name));
}
public Entity createEntity(String name, String text) {
return new EntityImpl(DocumentHelper.createEntity(name, text));
}
public Namespace createNamespace(String uri) {
return new NamespaceImpl(org.dom4j.Namespace.get(uri));
}
public Namespace createNamespace(String prefix, String uri) {
return new NamespaceImpl(DocumentHelper.createNamespace(prefix, uri));
}
public ProcessingInstruction createProcessingInstruction(
String target, Map<String, String> data) {
org.dom4j.ProcessingInstruction processingInstruction =
DocumentHelper.createProcessingInstruction(target, data);
if (processingInstruction == null) {
return null;
}
else {
return new ProcessingInstructionImpl(processingInstruction);
}
}
public ProcessingInstruction createProcessingInstruction(
String target, String data) {
org.dom4j.ProcessingInstruction processingInstruction =
DocumentHelper.createProcessingInstruction(target, data);
if (processingInstruction == null) {
return null;
}
else {
return new ProcessingInstructionImpl(processingInstruction);
}
}
public QName createQName(String localName) {
return new QNameImpl(DocumentHelper.createQName(localName));
}
public QName createQName(String localName, Namespace namespace) {
NamespaceImpl namespaceImpl = (NamespaceImpl)namespace;
return new QNameImpl(
DocumentHelper.createQName(
localName, namespaceImpl.getWrappedNamespace()));
}
public Text createText(String text) {
return new TextImpl(DocumentHelper.createText(text));
}
public XPath createXPath(String xpathExpression) {
return new XPathImpl(DocumentHelper.createXPath(xpathExpression));
}
public List<Node> selectNodes(
String xpathFilterExpression, List<Node> nodes) {
return toNewNodes(
DocumentHelper.selectNodes(
xpathFilterExpression, toOldNodes(nodes)));
}
public List<Node> selectNodes(
String xpathFilterExpression, Node node) {
NodeImpl nodeImpl = (NodeImpl)node;
return toNewNodes(
DocumentHelper.selectNodes(
xpathFilterExpression, nodeImpl.getWrappedNode()));
}
public void sort(List<Node> nodes, String xpathExpression) {
DocumentHelper.sort(toOldNodes(nodes), xpathExpression);
}
public void sort(
List<Node> nodes, String xpathExpression, boolean distinct) {
DocumentHelper.sort(toOldNodes(nodes), xpathExpression, distinct);
}
public Document read(File file) throws DocumentException {
return read(file, false);
}
public Document read(File file, boolean validate)
throws DocumentException {
try {
org.dom4j.io.SAXReader saxReader = getSAXReader(validate);
return new DocumentImpl(saxReader.read(file));
}
catch (org.dom4j.DocumentException de) {
throw new DocumentException(de.getMessage(), de);
}
}
public Document read(InputStream is) throws DocumentException {
return read(is, false);
}
public Document read(InputStream is, boolean validate)
throws DocumentException {
try {
org.dom4j.io.SAXReader saxReader = getSAXReader(validate);
return new DocumentImpl(saxReader.read(is));
}
catch (org.dom4j.DocumentException de) {
throw new DocumentException(de.getMessage(), de);
}
}
public Document read(Reader reader) throws DocumentException {
return read(reader, false);
}
public Document read(Reader reader, boolean validate)
throws DocumentException {
try {
org.dom4j.io.SAXReader saxReader = getSAXReader(validate);
return new DocumentImpl(saxReader.read(reader));
}
catch (org.dom4j.DocumentException de) {
throw new DocumentException(de.getMessage(), de);
}
}
public Document read(String xml) throws DocumentException {
return read(new XMLSafeReader(xml));
}
public Document read(String xml, boolean validate)
throws DocumentException {
return read(new XMLSafeReader(xml), validate);
}
public Document read(URL url) throws DocumentException {
return read(url, false);
}
public Document read(URL url, boolean validate) throws DocumentException {
try {
org.dom4j.io.SAXReader saxReader = getSAXReader(validate);
return new DocumentImpl(saxReader.read(url));
}
catch (org.dom4j.DocumentException de) {
throw new DocumentException(de.getMessage(), de);
}
}
public Document readURL(String url)
throws DocumentException, MalformedURLException {
return read(new URL(url), false);
}
public Document readURL(String url, boolean validate)
throws DocumentException, MalformedURLException {
return read(new URL(url), validate);
}
protected org.dom4j.io.SAXReader getSAXReader(boolean validate) {
org.dom4j.io.SAXReader reader = null;
try {
reader = new org.dom4j.io.SAXReader(new SAXParser(), validate);
reader.setEntityResolver(new EntityResolver());
reader.setFeature(_FEATURES_VALIDATION, validate);
reader.setFeature(_FEATURES_VALIDATION_SCHEMA, validate);
reader.setFeature(
_FEATURES_VALIDATION_SCHEMA_FULL_CHECKING, validate);
reader.setFeature(_FEATURES_DYNAMIC, validate);
}
catch (Exception e) {
if (_log.isWarnEnabled()) {
_log.warn(
"XSD validation is diasabled because " + e.getMessage());
}
reader = new org.dom4j.io.SAXReader(false);
reader.setEntityResolver(new EntityResolver());
}
return reader;
}
private static final String _FEATURES_VALIDATION =
"http://xml.org/sax/features/validation";
private static final String _FEATURES_VALIDATION_SCHEMA =
"http://apache.org/xml/features/validation/schema";
private static final String _FEATURES_VALIDATION_SCHEMA_FULL_CHECKING =
"http://apache.org/xml/features/validation/schema-full-checking";
private static final String _FEATURES_DYNAMIC =
"http://apache.org/xml/features/validation/dynamic";
private static Log _log = LogFactoryUtil.getLog(SAXReaderImpl.class);
private static SAXReaderImpl _instance = new SAXReaderImpl();
}

View File

@ -0,0 +1,50 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.xml;
import com.liferay.portal.kernel.xml.Text;
/**
* @author Brian Wing Shun Chan
*/
public class TextImpl extends NodeImpl implements Text {
public TextImpl(org.dom4j.Text text) {
super(text);
_text = text;
}
public boolean equals(Object obj) {
org.dom4j.Text text = ((TextImpl)obj).getWrappedText();
return _text.equals(text);
}
public org.dom4j.Text getWrappedText() {
return _text;
}
public int hashCode() {
return _text.hashCode();
}
public String toString() {
return _text.toString();
}
private org.dom4j.Text _text;
}

View File

@ -0,0 +1,164 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.xml;
import com.liferay.portal.kernel.xml.Node;
import com.liferay.portal.kernel.xml.XPath;
import java.util.List;
/**
* @author Brian Wing Shun Chan
*/
public class XPathImpl implements XPath {
public XPathImpl(org.dom4j.XPath xPath) {
_xPath = xPath;
}
public boolean booleanValueOf(Object context) {
return _xPath.booleanValueOf(toOldContext(context));
}
public boolean equals(Object obj) {
org.dom4j.XPath xPath = ((XPathImpl)obj).getWrappedXPath();
return _xPath.equals(xPath);
}
public Object evaluate(Object context) {
return toNewContext(_xPath.evaluate(toOldContext(context)));
}
public String getText() {
return _xPath.getText();
}
public org.dom4j.XPath getWrappedXPath() {
return _xPath;
}
public int hashCode() {
return _xPath.hashCode();
}
public boolean matches(Node node) {
NodeImpl nodeImpl = (NodeImpl)node;
return _xPath.matches(nodeImpl.getWrappedNode());
}
public Number numberValueOf(Object context) {
return _xPath.numberValueOf(toOldContext(context));
}
public List<Node> selectNodes(Object context) {
return SAXReaderImpl.toNewNodes(
_xPath.selectNodes(toOldContext(context)));
}
public List<Node> selectNodes(Object context, XPath sortXPath) {
XPathImpl sortXPathImpl = (XPathImpl)sortXPath;
return SAXReaderImpl.toNewNodes(
_xPath.selectNodes(
toOldContext(context), sortXPathImpl.getWrappedXPath()));
}
public List<Node> selectNodes(
Object context, XPath sortXPath, boolean distinct) {
XPathImpl sortXPathImpl = (XPathImpl)sortXPath;
return SAXReaderImpl.toNewNodes(
_xPath.selectNodes(
toOldContext(context), sortXPathImpl.getWrappedXPath(),
distinct));
}
public Node selectSingleNode(Object context) {
org.dom4j.Node node = _xPath.selectSingleNode(toOldContext(context));
if (node == null) {
return null;
}
else {
return new NodeImpl(node);
}
}
public void sort(List<Node> nodes) {
_xPath.sort(SAXReaderImpl.toOldNodes(nodes));
}
public void sort(List<Node> nodes, boolean distinct) {
_xPath.sort(SAXReaderImpl.toOldNodes(nodes), distinct);
}
public String toString() {
return _xPath.toString();
}
public String valueOf(Object context) {
return _xPath.valueOf(toOldContext(context));
}
protected Object toNewContext(Object context) {
if (context == null) {
return null;
}
else if (context instanceof org.dom4j.Document) {
org.dom4j.Document document = (org.dom4j.Document)context;
return new DocumentImpl(document);
}
else if (context instanceof org.dom4j.Node) {
org.dom4j.Node node = (org.dom4j.Node)context;
return new NodeImpl(node);
}
else if (context instanceof List<?>) {
return SAXReaderImpl.toNewNodes((List<org.dom4j.Node>)context);
}
else {
return context;
}
}
protected Object toOldContext(Object context) {
if (context == null) {
return null;
}
else if (context instanceof DocumentImpl) {
DocumentImpl documentImpl = (DocumentImpl)context;
return documentImpl.getWrappedDocument();
}
else if (context instanceof NodeImpl) {
NodeImpl nodeImpl = (NodeImpl)context;
return nodeImpl.getWrappedNode();
}
else if (context instanceof List<?>) {
return SAXReaderImpl.toOldNodes((List<Node>)context);
}
else {
return context;
}
}
private org.dom4j.XPath _xPath;
}

View File

@ -0,0 +1,33 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.util.xml;
import java.util.Comparator;
import org.dom4j.Attribute;
/**
* @author Brian Wing Shun Chan
*/
public class AttributeComparator implements Comparator<Attribute> {
public int compare(Attribute attr1, Attribute attr2) {
String attr1Value = attr1.getValue();
String attr2Value = attr2.getValue();
return attr1Value.compareTo(attr2Value);
}
}

View File

@ -0,0 +1,127 @@
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.util.xml;
import java.util.Comparator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Element;
/**
* @author Brian Wing Shun Chan
*/
public class ElementComparator implements Comparator<Element> {
public int compare(Element el1, Element el2) {
String el1Name = el1.getName();
String el2Name = el2.getName();
if (!el1Name.equals(el2Name)) {
return el1Name.compareTo(el2Name);
}
String el1Text = el1.getTextTrim();
String el2Text = el2.getTextTrim();
if (!el1Text.equals(el2Text)) {
return el1Text.compareTo(el2Text);
}
List<Attribute> el1Attributes = el1.attributes();
List<Attribute> el2Attributes = el2.attributes();
if (el1Attributes.size() < el2Attributes.size()) {
return -1;
}
else if (el1Attributes.size() > el2Attributes.size()) {
return 1;
}
for (Attribute attr : el1Attributes) {
int value = _compare(
el2Attributes, attr, new AttributeComparator());
if (value != 0) {
return value;
}
}
List<Element> el1Elements = el1.elements();
List<Element> el2Elements = el2.elements();
if (el1Elements.size() < el2Elements.size()) {
return -1;
}
else if (el1Elements.size() > el2Elements.size()) {
return 1;
}
for (Element el : el1Elements) {
int value = _compare(el2Elements, el, new ElementComparator());
if (value != 0) {
return value;
}
}
return 0;
}
private int _compare(
List<Attribute> list, Attribute obj, Comparator<Attribute> comparator) {
int firstValue = -1;
for (int i = 0; i < list.size(); i++) {
Attribute o = list.get(i);
int value = comparator.compare(obj, o);
if (i == 0) {
firstValue = value;
}
if (value == 0) {
return 0;
}
}
return firstValue;
}
private int _compare(
List<Element> list, Element obj, Comparator<Element> comparator) {
int firstValue = -1;
for (int i = 0; i < list.size(); i++) {
Element o = list.get(i);
int value = comparator.compare(obj, o);
if (i == 0) {
firstValue = value;
}
if (value == 0) {
return 0;
}
}
return firstValue;
}
}

Some files were not shown because too many files have changed in this diff Show More